-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question197.java
47 lines (40 loc) · 1.29 KB
/
Question197.java
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
/*
* Given an array and a number k that's smaller than the length of the array, rotate the array to the right k elements in-place.
*/
public class Question197 {
/*
* Reverse the entire array.
* Reverse the first k elements.
* Reverse the remaining n-k elements, where n is the length of the array.
*/
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int k = 3;
rotate(nums, k);
for (int num : nums) {
System.out.print(num + " ");
}
}
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public static void rotate(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 0) {
throw new IllegalArgumentException("invalid input");
}
int n = nums.length;
k %= n;
// reverse the entire array
reverse(nums, 0, n - 1);
// reverse the first k elements
reverse(nums, 0, k - 1);
// reverse the remaining n-k elements
reverse(nums, k, n - 1);
}
}