Skip to content

Commit b1e8102

Browse files
committed
add 189
1 parent 2ef92ec commit b1e8102

File tree

3 files changed

+73
-1
lines changed

3 files changed

+73
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
| 26 | [Remove Duplicates from Sorted Array][026] |
1919
| 121 | [Best Time to Buy and Sell Stock][121] |
2020
| 122 | [Best Time to Buy and Sell Stock II][122] |
21-
| 189 | Rotate Array |
21+
| 189 | [Rotate Array][189] |
2222

2323

2424

@@ -29,3 +29,4 @@
2929
[026]: https://github.com/andavid/leetcode-java/blob/master/note/026/README.md
3030
[121]: https://github.com/andavid/leetcode-java/blob/master/note/121/README.md
3131
[122]: https://github.com/andavid/leetcode-java/blob/master/note/122/README.md
32+
[189]: https://github.com/andavid/leetcode-java/blob/master/note/189/README.md

note/189/README.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# [Rotate Array][title]
2+
3+
## Description
4+
5+
Rotate an array of n elements to the right by k steps.
6+
7+
For example, with n = 7 and k = 3, the array `[1,2,3,4,5,6,7]` is rotated to `[5,6,7,1,2,3,4]`.
8+
9+
**Note:**
10+
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
11+
12+
## 思路
13+
三步反转法
14+
15+
(X<sup>T</sup>Y<sup>T</sup>)<sup>T</sup> = YX
16+
17+
这里需要特别注意,向右移动的步数 k 有可能大于数组的长度,因此要做个取模处理。
18+
19+
## [完整代码][src]
20+
21+
```java
22+
class Solution {
23+
public void rotate(int[] nums, int k) {
24+
int n = nums.length;
25+
k %= n;
26+
reverse(nums, 0, n - k - 1);
27+
reverse(nums, n - k, n - 1);
28+
reverse(nums, 0, n - 1);
29+
}
30+
31+
private void reverse(int[] nums, int from, int to) {
32+
while (from < to) {
33+
int temp = nums[from];
34+
nums[from++] = nums[to];
35+
nums[to--] = temp;
36+
}
37+
}
38+
}
39+
```
40+
41+
[title]: https://leetcode.com/problems/rotate-array
42+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_189/Solution.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.andavid.leetcode._189;
2+
3+
public class Solution {
4+
public void rotate(int[] nums, int k) {
5+
int n = nums.length;
6+
k %= n;
7+
reverse(nums, 0, n - k - 1);
8+
reverse(nums, n - k, n - 1);
9+
reverse(nums, 0, n - 1);
10+
}
11+
12+
private void reverse(int[] nums, int from, int to) {
13+
while (from < to) {
14+
int temp = nums[from];
15+
nums[from++] = nums[to];
16+
nums[to--] = temp;
17+
}
18+
}
19+
20+
public static void main(String[] args) {
21+
Solution solution = new Solution();
22+
int[] nums = {1, 2, 3, 4, 5, 6, 7};
23+
solution.rotate(nums, 3);
24+
int len = nums.length;
25+
for (int i = 0; i < len; i++) {
26+
System.out.print(nums[i] + (i == len - 1 ? "" : ", "));
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)