취미처럼

[Codility] Lesson 2. Arrays - CyclicRotation 본문

Algorithm/Codility

[Codility] Lesson 2. Arrays - CyclicRotation

sirius 2020. 2. 19. 21:46

주어진 배열 A에서 정수 K만큼 배열의 차수를 올리되, 차수가 배열 길이 이상일 때 0부터 다시 시작한다.

 

public static int[] solution(int[] A, int K) {
  int answer[] = new int[A.length];
  for (int i = 0; i < A.length; i++) {
 	 answer[(i + K) % A.length] = A[i];
  }
  return answer;
}

 

int[] A = {0,3,4,2,5};
int K = 3;
answer 배열의 인덱스

 

(0 + 3) % 5 = 3      answer[3] = A[0];
(1 + 3) % 5 = 4      answer[4] = A[1];
(2 + 3) % 5 = 0      answer[0] = A[2];
(3 + 3) % 5 = 1      answer[1] = A[3];
(4 + 3) % 5 = 2      answer[2] = A[4];

int answer[] = {4,2,5,0,3};

Comments