Post

[Programmers] #120821 - 배열 뒤집기 [Java][C++][Python]

[Programmers] #120821 - 배열 뒤집기 [Java][C++][Python]

문제 링크


1. 아이디어

num_list의 원소의 순서를 거꾸로 뒤집은 배열을 반환하면 되는 간단한 문제다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(1)$

($N$ = num_list의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int[] solution(int[] num_list) {
        int n = num_list.length;
        for (int i = 0; i < n / 2; i++) {
            int tmp = num_list[i];
            num_list[i] = num_list[n - 1 - i];
            num_list[n - 1 - i] = tmp;
        }

        return num_list;
    }
}

앞뒤 인덱스(i, n - 1 - i)를 맞바꿔가며 num_list를 제자리에서 뒤집었다. 끝까지 돌면 이미 바꾼 쌍을 도로 바꾸게 되므로, 절반(n / 2)까지만 순회해야 한다.

1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> num_list) {
    reverse(num_list.begin(), num_list.end());
    return num_list;
}

std::reverse로 num_list를 제자리에서 뒤집었다.

1
2
3
def solution(num_list):
    num_list.reverse()
    return num_list

reverse로 num_list를 제자리에서 뒤집었다.


This post is licensed under CC BY 4.0 by the author.