-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRotateArray.java
More file actions
53 lines (46 loc) · 1.33 KB
/
RotateArray.java
File metadata and controls
53 lines (46 loc) · 1.33 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
package array;
/**
* Description: https://leetcode.com/problems/rotate-array
* Difficulty: Medium
*/
public class RotateArray {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public void rotateViaExtraArray(int[] nums, int k) {
k = k % nums.length;
if (k == 0) return;
int[] tmp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
tmp[(i + k) % tmp.length] = nums[i];
}
for (int i = 0; i < tmp.length; i++) {
nums[i] = tmp[i];
}
}
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public void rotateViaTripleReversal(int[] nums, int k) {
k = k % nums.length;
if (k == 0) return;
// k = 3
reverse(nums, 0, nums.length - 1); // 1 2 3 4 5 -> 5 4 3 2 1
reverse(nums, 0, k - 1); // 5 4 3 2 1 -> 3 4 5 2 1
reverse(nums, k, nums.length - 1); // 3 4 5 2 1 -> 3 4 5 1 2
}
private void reverse(int[] nums, int left, int right) {
while (left < right) {
swap(nums, left, right);
left++;
right--;
}
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}