Skip to content

Commit 72ff652

Browse files
committed
Rotate Array
1 parent 3d805cd commit 72ff652

3 files changed

Lines changed: 45 additions & 1 deletion

File tree

Array/Rotate-Array.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
##Rotate Array
2+
3+
Total Accepted: 64166 Total Submissions: 311000 Difficulty: Easy
4+
Rotate an array of n elements to the right by k steps.
5+
6+
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].
7+
8+
Note:
9+
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
10+
11+
####思路
12+
- 多次翻转
13+
- 注意问清面试官题意,自己在这个题意理解上错了好几次,这个rotate的意思就相当于在执行>>操作
14+
15+
```java
16+
public class Solution {
17+
public void rotate(int[] nums, int k) {
18+
int n = nums.length;
19+
if (k == 0) {
20+
return;
21+
}
22+
if (k >= n) {
23+
k = k % n;
24+
}
25+
26+
k = n - k;
27+
28+
reverse(nums, 0, k - 1);
29+
reverse(nums, k , n - 1);
30+
reverse(nums, 0, n - 1);
31+
}
32+
33+
public void reverse(int[] nums, int start, int end) {
34+
if (start >= end) return;
35+
36+
for (int i = start, j = end; i < j; i++, j--) {
37+
int temp = nums[i];
38+
nums[i] = nums[j];
39+
nums[j] = temp;
40+
}
41+
}
42+
}
43+
```

Java/notes.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ Compares its two arguments for order. Returns a negative integer, zero, or a pos
3838
- Different Ways to Add Parentheses
3939

4040
###Leetcode一轮虽然做对,但是花时有点长或者需要注意再重做的题
41-
- Remove Duplicates from Sorted Array
41+
- Remove Duplicates from Sorted Array I and II
4242

4343
###难题
4444

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ This is the summary of my experience in LintCode.
150150

151151

152152
* [Array](Array/README.md)
153+
* [Rotate Array](Array/Rotate-Array.md)
153154
* [Shortest Word Distance](Array/Shortest-Word-Distance.md)
154155
* [Shortest Word Distance II](Array/Shortest-Word-Distance-II.md)
155156
* [Shortest Word Distance III](Array/Shortest-Word-Distance-III.md)

0 commit comments

Comments
 (0)