티스토리 뷰

https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/

 

CyclicRotation coding task - Learn to Code - Codility

Rotate an array to the right by a given number of steps.

app.codility.com

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    public int[] solution(int[] A, int K) {
 
       if(A.length == 1) {
           return A;
        }
 
        int remainder = K % A.length;        //배열 길이만큼 rotation시키면 다시 처음 배열 상태로 돌아오기 때문에 나머지만 필요          
        int tempSize = A.length - remainder;
 
        int[] tempArr = new int[tempSize];        //뒤로 밀릴 숫자들 넣어두는 배열
        ArrayList<Integer> answerList = new ArrayList<>();
 
        for(int i = 0; i < A.length; i++) {
            if(i < tempSize) {
                tempArr[i] = A[i];
            } else {
                answerList.add(A[i]);
            }
        }
 
        for(int tempNum : tempArr) {
            answerList.add(tempNum);
        }
 
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

empty array까지 고려하란 말이 없었는데, 채점해보니 empty array때문에 점수가 깎였다.

그래서 A 배열의 길이로 empty array를 골라내주니 100% !!

배열 길이만큼 로테이션시키면 결국 다시 처음 배열로 돌아온다.

예를 들어 ([1,2,3], 3) 일 경우,

[3,1,2] -> 1

[2,3,1] -> 2

[1,2,3] -> 3

따라서 나머지만 가지고 로테이션 돌리면 된다.

tempArr 배열에 뒤로 밀릴 숫자들을 저장하고 새 ArrayList에 로테이션 순서에 맞춰 넣어주면 끝!

댓글