Rotate Array
来源:互联网 发布:首大耳鼻咽喉医院 知乎 编辑:程序博客网 时间:2024/06/05 06:38
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:
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.
思路:
题目要求是在一个数组中向右移动k步,求得最后的数组的结果.首先对这个k steps如果移动的是数组size的 倍数的话,整体效果是数组看到并没有被移动。因此,k%nums.szie()计为实际的移动步数。将数组分成两部分,两部分各自reverse以后再整体reverse一下就可以了
注意在使用reverse这个函数的时候,reverse的第一个参数是操作的起始位置,第二个位置是结束位置的下一个元素。
class Solution {public: void rotate(vector<int>& nums, int k) { int size=nums.size(); k%=size; if(k==0) //当K大于数组的size的时候直接返回,这个时候数组的数字的分布不会被改变 return ; reverse(nums.begin(),nums.begin()+size-k); //not <span style="font-family: Arial, Helvetica, sans-serif;">nums.begin()+size-k-1</span> reverse(nums.begin()+size-k,nums.end()); reverse(nums.begin(),nums.end()); }};
0 0
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- rotate array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- iOS tableviewcell代码创建&xib创建执行方法
- 如何在QT下打开一张图片
- YII自学笔记(四)
- 查看tomcat版本
- iOS项目的目录结构和开发流程
- Rotate Array
- 使用DirectShow驱动摄像头
- Android自定义View(三、深入解析控件测量onMeasure)
- autocomplete+ajax+json实现自动补全功能
- Ti IMGLIB库简介
- Windows下安装并设置Redis
- MFC相关问题汇总
- python使用tesseract-ocr完成验证码识别
- Spring定时任务的几种实现