[Programmers] #181891 - 순서 바꾸기 [Java][C++][Python]
[Programmers] #181891 - 순서 바꾸기 [Java][C++][Python]
1. 아이디어
앞의 $n$개를 뒤로 보내고 $n$번째 이후의 원소들을 앞으로 당기는 것이므로, 배열을 왼쪽으로 $n$칸 회전하는 것과 같다.
2. 코드
풀이 [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로 두 번째 인자의 원소가 새 시작이 되도록 구간을 회전시켰다.
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.