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
.
최근 풀이
index 에 대해 고민해보고 풀어봤다.
rotation과 관련한 문제를 풀 때는 전체 index와 옮겨지는index의 차이 및 합이
array의 length를 넘어가는 경우 재배치해주식으로 하면 쉽게 풀 수 있는 거 같다.
package datastructure;
import java.util.Scanner;
public class LeftRotation {
public static int[] arrayLeftRotation(int[] a, int n, int k) {
int[] results = new int[n];
for (int i = 0; i < n; i++){
if (i-k < 0){
results[n + (i-k)] = a[i];
} else {
results[i-k] = a[i];
}
}
return results;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int[] output = new int[n];
output = arrayLeftRotation(a, n, k);
for (int i = 0; i < n; i++)
System.out.print(output[i] + " ");
System.out.println();
}
}
풀이
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int[] copy = new int[n];
System.arraycopy(a, k, copy, 0, n-k);
System.arraycopy(a, 0, copy, n-k, k);
System.out.println(Arrays.toString(copy).replace("[", "").replace("]", "").replace(",", ""));
}
}
arraycopy 에 대한참고자료
http://forum.falinux.com/zbxe/index.php?document_srl=571358&mid=lecture_tip
'Algorithms > Cracking the Coding Interview' 카테고리의 다른 글
Queues: A Tale of Two Stacks (0) | 2018.02.20 |
---|---|
Stacks: Balanced Brackets (0) | 2018.02.19 |
Linked Lists: Detect a Cycle (0) | 2018.02.19 |
Hash Tables: Ransom Note (0) | 2018.02.09 |
Strings: Making Anagrams (0) | 2018.02.09 |