LeetCode-Rotate Array
原创
©著作权归作者所有:来自51CTO博客作者BeHelium的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
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]
Example 2:
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?
题意:给定一个一维数组和一个整数k,将这个一维数组向右循环移动k步,即最后一个元素移动到数组的首部,其他的向后移动;要求空间复杂度为O(1);
解法一:最简单的方法就是循环k次,每次向右移动一步,从数组尾部开始赋给它前一个元素的值,最后第一个元素赋给它最后一个元素的值;这里使用一个变量存储最后一个元素的值;
Java
class Solution {
public void rotate(int[] nums, int k) {
while (k-- > 0) {
int temp = nums[nums.length - 1];
for (int i = nums.length - 1; i > 0; i--) {
nums[i] = nums[i - 1];
}
nums[0] = temp;
}
}
}
解法二:假设我们要旋转的数组为nums=[x1,x2,x3,x4,x5,x6,x7],旋转的步数为k=3;那么我们可以这样求解;
- 将数组nums所有元素逆序,得到nums=[x7,x6,x5,x4,x3,x2,x1]
- 将数组前k个元素逆序,得到nums= [x5,x6,x7,x4,x3,x2,x1]
- 将数组的后nums.length - k个元素逆序,得到nums=[x5,x6,x7,x1,x2,x3,x4],即最终的答案
class Solution
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);
}
private void reverse(int[] nums, int st, int ed) {
while