CyclicRotation
Rotate an array to the right by a given number of steps.
Task Score
100%
Correctness
100%
Performance
Not assessed
맨 뒤의 숫자를 임시 변수에 저장했다가 나머지 숫자들을 뒤로 한 칸씩 미룬 뒤 맨 앞에 넣어주는 방식을 K번 반복했다.
performance 점수는 논외로 정확도만 본다고 했기 때문에 반복횟수를 고려하지않고 단순무식하게 생각해서 풀었다.
x
// you can also use imports, for example:// import java.util.*;// you can write to stdout for debugging purposes, e.g.// System.out.println("this is a debug message");class Solution { public int[] solution(int[] A, int K) { if (A.length == 0) return A; for (int i = 0; i < K; i++) { int temp = A[A.length - 1]; for (int j = A.length - 1; j > 0; j--) { A[j] = A[j - 1]; } A[0] = temp; } return A; }}
performance를 생각해서 풀면 다음과 같이 풀 수 있겠다.
만약 크기가 5인 배열을 3칸 씩 옮기는 거라고 하면 i → (i + 3) % 5로 이동하게 되므로
0 → 3, 1 → 4, 2 → 0, 3 → 1, 4 → 2
와 같은 식으로 이동하게 된다.
x
// you can also use imports, for example:// import java.util.*;// you can write to stdout for debugging purposes, e.g.// System.out.println("this is a debug message");class Solution { public int[] solution(int[] A, int K) { int[] arr = new int[A.length]; for (int i = 0; i < A.length; i++) arr[(i + K) % A.length] = A[i]; return arr; }}
'공부 > algorithm' 카테고리의 다른 글
| [codility] FrogJmp (0) | 2018.05.22 |
|---|---|
| [codility] OddOccurrencesInArray (0) | 2018.05.22 |
| [codility] BinaryGap (0) | 2018.05.22 |
| [programmers] 숫자의 표현 (0) | 2018.05.22 |
| [programmers] 멀리 뛰기 (0) | 2018.05.22 |
댓글