상세 컨텐츠

본문 제목

Codiliity Lesson2 - CyclicRotation

코딩테스트/코딜리티

by 허허지니 2023. 8. 8. 09:16

본문

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).

N개의 정수로 구성된 배열 A가 주어집니다. 배열의 회전은 각 요소가 한 인덱스만큼 오른쪽으로 이동하고 배열의 마지막 요소가 첫 번째 자리로 이동하는 것을 의미합니다. 예를 들어, 배열 A = [3, 8, 9, 7, 6]의 회전은 [6, 3, 8, 9, 7]입니다 (숫자는 한 인덱스만큼 오른쪽으로 이동하고 6은 첫 번째 자리로 이동합니다).

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

목표는 배열을 A번 회전하는 것입니다. 즉, A의 각 요소가 올바른 K번으로 이동합니다.

Write a function:

class Solution { public int[] solution(int[] A, int K); }

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

N개의 정수와 K개의 정수로 구성된 배열 A가 주어지면 배열 A가 K번 회전합니다.

For example, given

    A = [3, 8, 9, 7, 6]
    K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:

함수는 [9, 7, 6, 3, 8]로 반환되어야 합니다. 세 번의 회전이 이루어졌습니다:

    [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
    [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
    [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given

    A = [0, 0, 0]
    K = 1
the function should return [0, 0, 0]

함수는 [0, 0, 0]을 반환해야 합니다

Given

    A = [1, 2, 3, 4]
    K = 4
the function should return [1, 2, 3, 4]

함수는 [1, 2, 3, 4]로 반환되어야 합니다

Assume that:

N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

N과 K는 [0..100] 범위 내의 정수입니다;
배열 A의 각 요소는 [-1,000..1,000] 범위 내의 정수입니다.
솔루션에서는 정확성에 초점을 맞추십시오. 솔루션의 성능은 평가의 초점이 아닙니다.


2023.08.08
class Solution {
    public int[] solution(int[] A, int K) {
        int len = A.length;
        int[] answer = new int[len];
        int num = K % len;

        for(int i = 0; i < len; i++) {
            if(i < num) {
                answer[i] = A[len - num + i];
            } else {
                answer[i] = A[i - num];
            }
        }

        return answer;
    }
}

 - RUNTIME ERROR

class Solution {
    public int[] solution(int[] A, int K) {
        int len = A.length;
        if(len < 1) {
            return A;
        }
        
        int[] answer = new int[len];
        int num = K % len;

        for(int i = 0; i < len; i++) {
            if(i < num) {
                answer[i] = A[len - num + i];
            } else {
                answer[i] = A[i - num];
            }
        }

        return answer;
    }
}

 

'코딩테스트 > 코딜리티' 카테고리의 다른 글

Codility Lesson3 - FrogJmp  (0) 2023.08.08
Codility Lesson2 - OddOccurrencesInArray  (0) 2023.08.08
Codility Lesson1 - BinaryGap  (0) 2023.08.07
Codility 오류 정리  (0) 2023.08.07
코딜리티  (0) 2023.08.07

관련글 더보기