189. Rotate Array
2016-03-27 22:24
316 查看
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.
Related problem: Reverse Words in a String II
第一次将整个数组反转,第二次将前k个元素翻转,第三次将剩下的元素翻转。
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.
Related problem: Reverse Words in a String II
解答
三次翻转第一次将整个数组反转,第二次将前k个元素翻转,第三次将剩下的元素翻转。
class Solution { public: void rotate(vector<int>& nums, int k) { if(nums.empty()) return; int n = nums.size(); if(k == n) return; if(k>n) k = k%n; reverse(nums.begin(),nums.end()); vector<int>::iterator rotatePoint = nums.begin()+k; reverse(nums.begin(),rotatePoint); reverse(rotatePoint,nums.end()); } };
相关文章推荐
- uestc1131男神的礼物【dp】
- gets和scanf函数初篇
- 电话面试2 20160325_1733_27min
- c语言实现des加密
- 矩阵旋转
- 几句话弄清楚Java参数传值还是传引用
- codeforces 650C - Table Compression
- 20145206邹京儒《Java程序设计》第4周学习总结
- 从C10K到C10M高性能网络的探索与实践
- qt5.5程序打包发布以及依赖
- 字典树应用(5)HDU1247
- java int与integer的区别
- spring mvc 小结-51cto学院Spring MVC
- HDU 1045&ZOJ 1002 Fire Net (还是DFS呀...)
- c++实验2—标准体重
- Shaders: ShaderLab & Fixed Function shaders
- JavaScript 学习笔记——cssText
- 敏捷开发方法综述
- 除法取模(逆元)
- Android中handle用法总结