Post

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

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

문제 링크


1. 아이디어

배열을 뒤집는 문제다. 배열의 길이를 $n$이라 하면 인덱스 $i$와 $n - 1 - i$의 원소를 맞바꾸면 되는데, $i$가 $\lfloor n / 2 \rfloor$ 미만인 앞쪽 절반에서만 하면 된다(홀수 길이면 가운데 원소는 제자리다). 끝까지 돌리면 이미 맞바꾼 쌍을 다시 되돌리게 된다.


2. 코드

풀이 [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;
    }
}
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로 맞바꾸는 반복 없이 구간을 한 번에 뒤집었다.

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

reverse로 리스트를 제자리에서 바로 뒤집었다.


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