티스토리 뷰

알고리즘

[codility] 레슨2-1 CyclicRotation

Gibson 김형섭 2018. 3. 7. 00:10

코딜리티 알고리즘 연습 두번째 포스팅.


A zero-indexed 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:

struct Results solution(int A[], int N, int K);

that, given a zero-indexed 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.

Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.


문제해석


A 정수배열에 있는 값을 K번만큼 오른쪽으로 밀기.


ex)

A = [1, 2, 3, 4]

K = 1

이면

return [4, 1, 2, 3] 


A = [1, 2, 3, 4]

K = 4

이면

return [1, 2, 3, 4]



단순 문제해결에 집중한 첫번째 시도는 단순하게 K번 만큼 루프를 돌리고 

배열의 값들을 옮겨주는 루프를 돌리는 방법으로 풀었더니.. 


시간복잡도 때문에 스코어 87%가 나왔다.


오늘도 100%를 달성하기 위해 고민고민하다 루프를 배열길이만큼 한번만 돌리게 수정했다.



결과는 100% 달성..!



풀이 





class Solution { public int[] solution(int[] A, int K) { // write your code in Java SE 8 int arraySize = A.length; int result[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) { result[(i + K) % arraySize] = A[i]; } return result; } }




처음부터 너무 복잡하게 생각했었다.


인자로 받은 배열은 유지하고 새로운 배열을 만들어서 

배열 길이만큼 루프돌리고,

(i + K) % arraySize 로 K번만큼 돌았다고 가정해서 인덱스를 구해준 뒤 A[i] 값을 넣어주면 끝.






'알고리즘' 카테고리의 다른 글

[codility] 레슨2-2 OddOccurrencesInArray  (1) 2018.03.07
[codility] 레슨1 BinaryGap  (0) 2018.03.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함