题目描述:
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]
.
思路分析:将数组分为左右两部分,先将左右两部分各自翻转,最后再将整个数组整体翻转,即得结果。
代码:
class Solution
{
public:
void swap(int * a,int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void rotate(vector<int> & nums,int k)
{
int length = nums.size();
int l = length - (k % length);
int r = k % length;
for(int i = 0,j = l - 1;i < j;i++,j--)
swap(&nums[i],&nums[j]);
for(int i = l,j = length - 1;i < j;i++,j--)
swap(&nums[i],&nums[j]);
for(int i = 0,j = length - 1;i < j;i++,j--)
swap(&nums[i],&nums[j]);
}
};