Given an array, rotate the array to the right by k steps, where k is non-negative.
Example:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
解釋下題目:
數(shù)組的數(shù)字往后推移k位,如果超出了最后則接到頭部
1. 倒置的方法
實際耗時:0ms
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
踩過的坑:[-1] k=2
??我自己想到的思路是有三種,第一種是,搞個函數(shù),然后這個函數(shù)的作用是每次給數(shù)組后退1格,然后如果是k的話就重復(fù)k次,這樣時間是O(nk) 不需要額外的空間。第二種是再開辟一個同樣大小的數(shù)組,很簡單。最后一種就是上面代碼里的,其實這種rotate的題目最后都可以用倒序來實現(xiàn)。
時間復(fù)雜度O(n)
空間復(fù)雜度O(1)
| 表名1 | 表名2 |
|---|