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:
class Solution { public int[] solution(int[] A, int 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.
Copyright 2009–2023 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
// 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) {
// Implement your solution here
List<Integer> list = new ArrayList<>();
for(int i:A){
list.add(i);
}
Collections.rotate( list, K);
int size = list.size();
int[] answer = new int[size];
for (int i = 0 ; i < list.size() ; i++) {
answer[i] = list.get(i).intValue();
}
return answer;
}
}
문제를 그냥 보면 배열을 하나하나 다 이동해야하나 싶었는데, 여러가지 방법 중에 나는 자바에서 제공하는 List 의 rotate() 를 이용하여 풀이하였다.
이 방법을 사용하기위해서는 우선 배열을 List나 ArrayList로 변경하는 작업이 필요하다.
// String 배열의 경우
String[] arr = { "A", "B", "C" };
List<String> list = Arrays.asList(arr);
// int 배열의 경우
String[] arr = { 1, 2, 3 };
List<Integer> list = new ArrayList<>();
for(int i:A){
list.add(i);
}
String과 int의 배열 변환 방법이 다르다..int배열에는 Arrays.asList()를 사용하면 에러가 난다.
Collections.rotate( list, K);
Collections.rotate() 는 맨 뒤의 요소를 맨 앞으로 집어넣는 메소드이다.
해당하는 배열과 몇번 반복할건지를 입력하면 풀이와 같이 배열이 변경된다.
int size = list.size();
int[] answer = new int[size];
for (int i = 0 ; i < list.size() ; i++) {
answer[i] = list.get(i).intValue();
}
정수 배열의 크기를 변환된 list의 크기로 지정해주고 list의 각각의 요소를 정수 배열에 입력해주면 된다.