티스토리 뷰

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

 

내 코드

- 정상작동하지만 solution([], 1)에는 error를 발생시킴.

- 따라서 배열의 길이가 0일때는 while문에 들어가지 않고 바로 return하는 if조건문을 초반에 삽입해야 함.

- 이 코드의 문제는, 배열의 길이만큼 rotate할 때, 0번 한것과 같음에도 불구하고, 5번을 실행하기 때문에 프로그램이 길어진다는 것.

class Solution {
    public int[] solution(int[] A, int K) {
        if (A.length == 0) { //solution([], 1) 일 경우 대비하기
            return A;
        }
        
        while (K > 0) {
            int sto = A[0]; 
            int dto = sto;
            A[0] = A[A.length - 1];
            for (int i = 1; i < A.length; i++) {
                dto = A[i];
                A[i] = sto;
                sto = dto;
                
            }
            K--;
        }
        return A;
    }
}

 

내 코드 수정 

 

    public static int[] solution(int[] A, int K) {
        
        if (A.length == 0) { // 배열의 값이 0일경우 처리
            return A;
        }
        if (A.length % K == 0) { // 배수는 결국 배열의 변동이 없음.
            return A;
        }
        else if (K > A.length) { // K값이 커질경우 K % A.length번 시행한것과 같기 때문에, 실행속도를 줄여줌.
            K = K % A.length;
        }
        
        while (K > 0) {
            int sto = A[0]; 
            int dto = sto;
            A[0] = A[A.length - 1];
            for (int i = 1; i < A.length; i++) {
                dto = A[i];
                A[i] = sto;
                sto = dto;
                
            }
            K--;
        }
        return A;
    }
}

 

 

베스트 코드

 

* 느낀점

 - 0값 처리를 항상 염두해두기

 - 로테이션 반복을 할 때는 단순히 코드 짜는데만 집중하지 말고, 시간복잡도를 고려하여 생각하기.

'Algorithm > Codility' 카테고리의 다른 글

Codility -6 TapeEquilibrium(Java)  (0) 2020.03.05
Codility -5 PermMissingElem  (0) 2020.03.05
Codility -4 FrogJmp  (0) 2020.03.04
Codility -3 OddOccurrencesInArray(Java)  (0) 2020.03.04
Codility -1 Binary gap(Java)  (0) 2020.03.03
댓글