Rotate Array--LeetCode
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]
.
思路:三次翻转。
#include <iostream>
#include <vector>
using namespace std;
void RotateArray(vector<int>& vec,int k)
{
int size = vec.size();
int i,j;
for(i=0,j=size-k-1;i<=j;i++,j--)
swap(vec[i],vec[j]);
for(i=size-k,j=size-1;i<=j;i++,j--)
swap(vec[i],vec[j]);
for(i=0,j=size-1;i<=j;i++,j--)
swap(vec[i],vec[j]);
}
int main()
{
int array[]={1,2,3,4,5,6,7};
vector<int> vec(array,array+sizeof(array)/sizeof(array[0]));
RotateArray(vec,3);
int i=0;
for(i=0;i<vec.size();i++)
cout<<vec[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
还没有评论,来说两句吧...