Codility Lesson 2 Array - CycleRotation


문제

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:

function solution(A, 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.


문제해설 : 배열 A는 N개의 integers로 구성되어 있다. 배열의 Rotation은 각 배열의 요소가 한개씩 오른쪽 index로 이동하는 것을 의미한다. 그리고 마지막 index의 요소는 첫번째 index 요소로 이동한다.
예를 들면 A = [3,8,9,7,6] 은 [6,3,8,9,7]로 Rotation 된다.
이 문제의 목표는 배열 A가 K번 rotate하는 결과값을 리턴한다.

주의사항 :

  • N과 K는 [0, 100]의 범위를 가지는 integer이다.
  • 각 A배열의 요소emfdms -1000 ~ 1000의 범위의 integer로 구성되어져 있다.

답안 해설

작성코드 :

  • js
1
2
3
4
5
6
7
8
9
function solution(A, K) {
while(K > 0) {
var last = A[A.length-1];
A.unshift(last);
A.pop();
K--;
}
return A;
}

주어진 Rotation횟수 K는 0 ~ 100까지의 수이므로 while 반복문 내에서 배열의 요소들을 계속해서 Rotate 할 수 있다.
while문 내부에서는 last에 배열의 마지막 인덱스값을 할당하고 unshift() 함수를 통해 배열의 맨 앞으로 보낸다.
그 후 배열의 마지막 요소를 pop() 함수를 통해 제거한다.
마지막으로 K를 감소시킨다.
이 함수는 주어진 배열 A에서 K만큼만 배열의 요소를 움직이므로 시간복잡도는 O(N)이다.

실행결과

Lesson 2 CycleRotation Codility ResultLesson 2 CycleRotation Codility Result