Left Rotation
A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become .
Given an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
Input Format
The first line contains two space-separated integers denoting the respective values of (the number of integers) and (the number of left rotations you must perform).
The second line contains space-separated integers describing the respective elements of the array's initial state.
Constraints
Output Format
Print a single line of space-separated integers denoting the final state of the array after performing left rotations.
Sample Input
5 4
1 2 3 4 5
Sample Output
5 1 2 3 4
Explanation
When we perform left rotations, the array undergoes the following sequence of changes:
Thus, we print the array's final state as a single line of space-separated values, which is 5 1 2 3 4
.
풀이
아마 이전에는 System에서 array copy라는 자체 메소드로 풀었던 것 같다.
다만 실제 코딩 인터뷰를 볼 때에는 자체 메소드로 구현하는 것을 금지하거나 좋아하지는 않기 때문에
자체적으로 구현하는 게 더 좋을 거 같다.
정리해보면
- 입력받는 n으로 int 배열의 크기가 정해진다
- 입력받는 d의 값으로 기존 배열의 index가 왼쪽으로 d만큼 움직이게 된다(이게 핵심)
- StringBuilder 는 단일스레드에서 StringBuffer 보다 빠르고, String 에서 + 연사자를 이용하는 것보다 좋다는 글을 봐서 사용했음
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String[] nd = scan.nextLine().split(" ");
int n = Integer.parseInt(nd[0].trim());
int d = Integer.parseInt(nd[1].trim());
int[] a = new int[n];
String[] aItems = scan.nextLine().split(" ");
for (int aItr = 0; aItr < n; aItr++) {
int aItem = Integer.parseInt(aItems[aItr].trim());
a[aItr] = aItem;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++){
int index = (i + d) % n;
sb.append(String.valueOf(a[index])).append(" ");
}
System.out.println(sb.toString());
}