Leecode | Rotate Array
来源:互联网 发布:流程的优化分类 编辑:程序博客网 时间:2024/06/01 09:26
Rotate Array
Total Accepted: 26104 Total Submissions: 146721My SubmissionsRotate 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.
题目说多想几种方法,额,目前只想到一个好像==,而且WA了n多次。。。
我的思路:将旋转后的左半部分和右半部分分别存起来,然后清空原来的数组,push进去左半部分和右半部分,就得到目标数组了。还有其他方法,我想到并且AC了再补充。。
程序:
class Solution {public: void rotate(vector<int>& nums, int k) { if(k==0) return; while(k<0) k+=nums.size(); if(k>nums.size()) k%=nums.size(); vector<int> temp1; //两部分,分别存vector的前部分和后部分 vector<int> temp2; vector<int>::iterator lam; for(lam=nums.begin();lam!=nums.end();lam++) { temp1.push_back(*lam); } for(int i=0;i<k;i++) { temp2.push_back(temp1.back()); temp1.pop_back(); } nums.clear(); //清空 vector<int>::reverse_iterator p=temp2.rbegin(); for(;p!=temp2.rend();p++) { nums.push_back(*p); } vector<int>::iterator pp=temp1.begin(); for(;pp!=temp1.end();pp++) { nums.push_back(*pp); } }};
0 0
- Leecode | Rotate Array
- LeeCode-Rotate Array
- [Leecode 61] Rotate List
- LeeCode 61 Rotate List
- 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
- 数据挖掘10大算法(1)——PageRank
- for循环用struts2的bean标签实现
- 处理文本文件什么的,python最好用了
- Windows Phone 8.1中数据绑定之一
- java中压缩文件
- Leecode | Rotate Array
- 阴影映射(Shadow Map)的研究(五)
- UI设计之--仿微信聊天界面
- 如何构建学者的特征模型
- selenium 点击页面链接测试
- UICollectionView高级使用示例之CircleLayout
- Netflix公布个性化和推荐系统架构
- Android 模拟器和键盘的按键对应关系
- Linux学习笔记(05-25)读写锁