题目:
给定一个数组,将该数组向右旋转k步,其中k是非负的。
Given an array, rotate the array to the right by k steps, where k is non-negative.
Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Input: [-1,-100,3,99] and k = 2 Output: [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将数组分为两个部分,分别是0~k-1和k~len-1,先分别将两个部分的数组颠倒,再将整个数组颠倒,可得到所要求的数组
同【剑指offer第二版——面试题58(java)】——https://blog.csdn.net/qq_22527013/article/details/91371032
【注意】当k大于数组长度时,根据结果可见是需要将k视为k%nums.length再进行旋转
(也可先旋转整体数组,再重新旋转子数组)
代码:
class Solution {
public void rotate(int[] nums, int k) {
k = k%nums.length;
rotateAll(nums, 0, nums.length-1-k);
rotateAll(nums, nums.length-k,nums.length-1);
rotateAll(nums, 0, nums.length-1);
}
public void rotateAll(int[] nums, int start, int end) {
if(start<end) {
while(start<end) {
int temp = nums[end];
nums[end] = nums[start];
nums[start] = temp;
end--;
start++;
}
}
}
}