Rotate Array--LeetCode

忘是亡心i 2022-08-07 12:58 265阅读 0赞

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].

思路:三次翻转。

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. void RotateArray(vector<int>& vec,int k)
  5. {
  6. int size = vec.size();
  7. int i,j;
  8. for(i=0,j=size-k-1;i<=j;i++,j--)
  9. swap(vec[i],vec[j]);
  10. for(i=size-k,j=size-1;i<=j;i++,j--)
  11. swap(vec[i],vec[j]);
  12. for(i=0,j=size-1;i<=j;i++,j--)
  13. swap(vec[i],vec[j]);
  14. }
  15. int main()
  16. {
  17. int array[]={1,2,3,4,5,6,7};
  18. vector<int> vec(array,array+sizeof(array)/sizeof(array[0]));
  19. RotateArray(vec,3);
  20. int i=0;
  21. for(i=0;i<vec.size();i++)
  22. cout<<vec[i]<<" ";
  23. cout<<endl;
  24. system("pause");
  25. return 0;
  26. }

发表评论

表情:
评论列表 (有 0 条评论,265人围观)

还没有评论,来说两句吧...

相关阅读

    相关 translate与rotate

    今天在做旋转动画时,发现translate与rotate的顺序会对效果产生影响, 在此之前我以为顺序可以随便放的 理想情况是绕球体旋转,效果如下图 ![在这里插入图片