https://app.codility.com/demo/results/trainingGMRE4Z-JBU/
배열 A의 원소들을 K회 만큼 뒤로 밀었을때의 결과를 구하는 문제이다.
K회 만큼 loop를 돌려도 되지만,
원소들을 K회 만큼 뒤로 밀었을 때의 index 값은 (현재 index + K) 를 A 크기만큼 나눈 나머지임을 알 수 있으므로,
// 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 len = A.length;
if (len < 2 || K % len == 0) return A;
int[] answer = new int[len];
for (int i = 0; i < len; i++) {
int index = (i + K) % len;
answer[index] = A[i];
}
return answer;
}
}
'코딩테스트 > codility' 카테고리의 다른 글
PermCheck (0) | 2023.09.29 |
---|---|
TapeEquilibrium (0) | 2023.09.18 |
OddOccurrencesInArray (0) | 2023.09.16 |
BinaryGap (0) | 2023.09.07 |
MaxDoubleSliceSum (0) | 2023.08.23 |