Rotate an array of n elements to the right by k steps.
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]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
例如,n = 7 ,k = 3,数组 [1,2,3,4,5,6,7] 旋转成 [1,2,3,4,5,6,7]。
说明:
用尽可能多的方法实现。
分析:
法1:一个元素一个元素移动,需要将整个数组移动 k 次,效率低。
法2:先翻转前面的 (n-k)个数,再翻转后面的 k 个数,再将整个数组翻转。
法3:先整体反转,再将两部分分别翻转。
注意:翻转 n 步和翻转前事一样的,所以 k = k % n;
class Solution {
public:
void rotate(vector& nums, int k) {
if(nums.empty() || k == 0)
return;
int numSize = nums.size();
k = k % numSize; //大于数组长度时会循环移动
int left = 0, right = 0;
int i, j, temp = 0;
for(i = 0, j = numSize - k -1; i < j; ++i, --j) //交换前半部分
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for(i = numSize - k, j = numSize - 1; i < j; ++i, --j)//反转后半部分
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for(i = 0, j = numSize -1; i < j; ++i, --j)//整体反转
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return;
}
};