A left rotation operation on an array shifts each of the array's elements unit to the left. For example, if left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. Note that the lowest index item moves to the highest index in a rotation. This is called a circular array.
Given an array a of n integers and a number, d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.
Function Description
Complete the function rotLeft in the editor below.
rotLeft has the following parameter(s):
- int a[n]: the array to rotate
- int d: the number of rotations
Returns
- int a'[n]: the rotated array
Input Format
The first line contains two space-separated integers n and d, the size of a and the number of left rotations.
The second line contains n space-separated integers, each an a[i].
Constraints
- 1 <= n <= 105
- 1 <= d <= n
- 1 <= a[i] <= 106
Sample Input
5 4
1 2 3 4 5
Sample Output
5 1 2 3 4
Explanation
When we perform d = 4 left rotations, the array undergoes the following sequence of changes:
[1,2,3,4,5] -> [2,3,4,5,1] -> [3,4,5,1,2] -> [4,5,1,2,3] -> [5,1,2,3,4]
5 4 1 2 3 4 5 5 1 2 3 4 ...Program finished with exit code 0 Press ENTER to exit console.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static int[] rotLeft(int[] a, int d, int n) {
int i, j, k, b[] = new int[n], c[] = new int[n];
for(i = d, j = 0, k = 0; j < n; j++){
b[j] = a[j];
if(j > d-1){
a[k] = a[i];
k++;
i++;
}
else{
c[j] = b[j];
}
}
for(i = n-d, j = 0; i < n; i++, j++){
a[i] = c[j];
}
return a;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
int[] a = new int[n];
String[] aItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int aItem = Integer.parseInt(aItems[i]);
a[i] = aItem;
}
int[] result = rotLeft(a, d, n);
for (int i = 0; i < result.length; i++) {
bufferedWriter.write(String.valueOf(result[i]));
if (i != result.length - 1) {
bufferedWriter.write(" ");
}
}
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
5 4 1 2 3 4 5 5 1 2 3 4 ...Program finished with exit code 0 Press ENTER to exit console.
No comments:
Post a Comment