Post

[Programmers] #181891 - 순서 바꾸기 [Java][C++][Python]

정수 리스트를 n번째 지점에서 잘라 앞뒤 두 조각의 순서를 바꿔 이어 붙인 리스트를 구하는 워밍업 문제.

[Programmers] #181891 - 순서 바꾸기 [Java][C++][Python]

문제 링크


1. 아이디어

정수 리스트 num_list를 인덱스 n을 기준으로 두 조각으로 나눈 뒤, 뒤쪽 조각(n번째 원소부터 끝까지)을 앞에, 앞쪽 조각(처음 n개)을 뒤에 두어 이어 붙이면 된다. 리스트를 왼쪽으로 n칸 회전시킨 것과 같다.


2. 복잡도

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

($N$ = num_list의 길이)


3. 코드

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

1
2
3
4
5
6
7
8
class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] ans = new int[num_list.length];
        System.arraycopy(num_list, n, ans, 0, num_list.length - n);
        System.arraycopy(num_list, 0, ans, num_list.length - n, n);
        return ans;
    }
}
1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;

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

std::rotate(first, middle, last)[first, last) 구간을 middle이 맨 앞에 오도록 제자리에서 회전시킨다. middlenum_list.begin() + n으로 주면 n번째 원소가 앞으로 오고 처음 n개가 뒤로 밀려, 왼쪽으로 n칸 회전한 결과가 된다. num_list가 직접 바뀌므로 그대로 반환했다.

1
2
def solution(num_list, n):
    return num_list[n:] + num_list[:n]

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