-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateArray.java
More file actions
27 lines (25 loc) · 697 Bytes
/
RotateArray.java
File metadata and controls
27 lines (25 loc) · 697 Bytes
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
package leetcode.array;
/**
* @ClassName RotateArray
* @Description 旋转数组 https://leetcode-cn.com/problems/rotate-array/
* @Author changxuan
* @Date 2021/1/8 下午9:31
**/
public class RotateArray {
public void rotate(int[] nums, int k) {
k %= nums.length;
// 分解为三个反转
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start += 1;
end -= 1;
}
}
}