An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times
In your solution, focus on correctness.
이 문제는 입력받은 배열을 Rotate 시키는 알고리즘을 짜는 것이다. 문제에서 정확도를 신경쓰라고 했기 때문에, 가장 간단한 알고리즘인 O(N^2) 시간복잡도로 구현해보았다.
단순히 배열을 한칸씩 Rotate 시키는 함수를 따로 모듈화 해서 간단한 코드를 구현했다.
정확도를 위해서 신경써야할 부분은 공백 배열이 들어올 경우이다.
물론 배열 원소가 하나일때도 따로 취급하여 조금의 시간 복잡도 이득을 볼 수 있기 하였다.
공백 배열 (배열의 길이가 0) or 원소 하나짜리 배열(배열의 길이가 1) 일때는 input 그대로 Return 해주면 된다.
class Solution {
public int[] solution(int[] A, int K) {
if(A.length == 0 || A.length == 1){
return A;
}
else{
for(int i = 0; i < K; i++){
Rotate(A);
}
return A;
}
}
public int[] Rotate(int[] A){
int tmp = A[A.length-1];
for(int i=(A.length-2); i>=0; i--){
A[i+1] = A[i];
}
A[0] = tmp;
return A;
}
}
'Algorithm' 카테고리의 다른 글
[Codility] PermMissingElem (0) | 2019.05.30 |
---|---|
[Codility] FrogJmp (0) | 2019.05.30 |
[Codility] OddOccurencesInArray (0) | 2019.05.28 |
[Codility] BinaryGap (0) | 2019.05.28 |
[백준] 11399 ATM (0) | 2019.05.28 |