# 189 Rotate Array

## Rotate Array

Python代码：

class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]

#### Solution中的几种解法：

##### 3 Using Cyclic Replacements

1, 2, 3, 4, 5, 6, 7轮转三次：

1, 2, 3, 1, 5, 6, 7  temp=4
1, 2, 3, 1, 5 ,6 ,4  temp=7
1, 2, 7, 1, 5, 6, 4  temp=3
1, 2, 7 ,1, 5, 3, 4  temp=6
1, 6, 7, 1, 5, 3, 4  temp=2
1, 6, 7, 1, 2, 3, 4  temp=5
5, 6, 7, 1, 2, 3, 4

$n/k$$n/k$为整数时会要被替换的元素是我们第一次要替换元素的情况，如图：

public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int count = 0;
for (int start = 0; count < nums.length; start++) {//外部的循环，上图中的红色、绿色循环
int current = start;
int prev = nums[start];
do {
int next = (current + k) % nums.length;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);//内部的小循环，1，3，5元素间的相互替换
}
}
}
##### 4 Using Reverse

Original List                   : 1 2 3 4 5 6 7
After reversing all numbers     : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result

• 评论

• 上一篇
• 下一篇