-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayRotate.java
More file actions
59 lines (43 loc) · 1.53 KB
/
Copy pathArrayRotate.java
File metadata and controls
59 lines (43 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
//Given an array, review the final array after a number of rotations
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong(); //num of elements in the array
long k = in.nextInt(); //num of times to rotate array
int q = in.nextInt(); //num of elements to be printed out
long [] arr = new long [n];
//populate the array
for (int i = 0; i < n; i++) {
arr[i] = in.nextLong();
}
//perfom the rotation
for(int j = 0; j < k; j++) {
rotate(arr);
}
//print the ints at index m
for(int c = 0; c < q; c++) {
int m = in.nextInt();
System.out.println(arr[m]);
}
in.close();
}
public static void rotate(Long [] arr) {
long temp = arr[arr.length - 1];
for(int i = arr.length - 2; i >= 0; i--) {
arr[i + 1] = arr[i];
}
arr[0] = temp;
}
}
//A faster way to solve this would have been to find a
//a mathematical way to to work how the indexes work
//rather than rotating all the elements because that has O(n)
//where n is the number of rotations, imagine if there was an incredibly large number
//of rotations
//TO-DO
// I will pull up the suggested solution from hackerank and explain it