[Codility] CyclicRotation

2025. 11. 22. 18:19CS & Algorithm/문제풀이

https://app.codility.com/c/run/trainingY84P8Z-PRG/ 

 

Codility

Your browser is not supported Please, update your browser or switch to a different one. Learn more about what browsers are supported

app.codility.com

번역본

 

접근 방식

  • 배열을 오른쪽으로 K번 회전시키는 문제로 “단순히 K번 반복해서 배열을 밀어내는 방식”은 비효율적! 
  • 인덱스 수학 공식으로 해결 가능 
  • newIndex = (i + K) % N
  • 기존 배열을 수정하지 않고, 새로운 배열을 만들어서 해당 배열에 인덱스에 맞는 값을 할당

나의 풀이 코드

public int[] solution(int[] A, int K) {

    // K가 0이거나 배열이 비어 있는 경우 그대로 반환
    if (K == 0 || A.length == 0) {
        return A;
    }

    int arrayLength = A.length;
    int[] result = new int[arrayLength];

    // 각 요소가 이동해야 할 위치 계산
    for (int i = 0; i < arrayLength; i++) {
        int newIndex = (i + K) % arrayLength;
        result[newIndex] = A[i];
    }

    return result;
}

 

리팩토링 코드 or 다른 방식의 풀이 코드

public int[] solution(int[] A, int K) {

    int n = A.length;

    // 예외 처리: 빈 배열
    if (n == 0) {
        return A;
    }

    // K가 배열의 길이보다 크면 줄이기
    K = K % n;

    // 회전할 필요가 없는 경우
    if (K == 0) {
        return A;
    }

    int[] result = new int[n];

    for (int i = 0; i < n; i++) {
        result[(i + K) % n] = A[i];
    }

    return result;
}