[codility/java] 2-1. CyclicRotation

jyleever·2022년 8월 12일
0

알고리즘

목록 보기
21/26

문제

https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
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.

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.

For example, given

A = [3, 8, 9, 7, 6]
K = 3

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

[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]

Given

A = [1, 2, 3, 4]
K = 4

the function should return [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번 이동했을 때의 배열 구하기
  • 해당 규칙은 다음과 같이 간단한 점화식으로 나타낼 수 있다.
    예를 들어 N = 5, K = 3이라면
    0 -> 3 1 -> 4 2 -> 0 3 -> 1 4 -> 2 5 -> 3
    즉 i번째 원소는 (i+K) % N 번째로 이동함

코드

/**
배열의 값을 오른쪽으로 k번 이동했을 때의 배열의 값을 구하라

예를 들어 N = 5, K = 3이라면 0 -> 3 1 -> 4 2 -> 0 3 -> 1 4 -> 2 5 -> 3
즉 (i+K) % N
**/
class Solution {
    public int[] solution(int[] A, int K) {
        
        int N = A.length;
        int[] ans = new int[N];

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

        return ans;
    }
}

0개의 댓글