leetcode-189.-Rotate Array
来源:互联网 发布:tbi文件怎么导入淘宝 编辑:程序博客网 时间:2024/04/30 01:46
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.
将数组向右旋转k步。例如,[1,2,3,4,5,6,7] 旋转一步变为[7,1,2,3,4,5,6] 。
利用队列,在队列里旋转好之后,再赋值到vector里。
class Solution {public: void rotate(vector<int>& nums, int k) { queue<int>q ; int n = nums.size(); // 在vector里的元素放进队列里 for (int i = 0 ; i < n ; i ++) { q.push(nums.back()) ; nums.pop_back(); } //将队列的元素进行rotate for (int i = 0 ; i < k ; i ++) { int t = q.front() ; q.pop() ; q.push(t) ; } //在将队列里的元素赋值到原vector里 for (int i = 0 ; i < n ; i ++) { nums.push_back(q.front()) ; q.pop() ; } for (int i = 0 ;i<n/2;i++) swap(nums[i],nums[n-i-1]) ; }};
0 0
- [LeetCode]189.Rotate Array
- [Leetcode] 189.Rotate Array
- LeetCode 189. Rotate Array
- 【LeetCode】189.Rotate Array
- [leetcode] 189.Rotate Array
- 【leetcode】189. Rotate Array
- Leetcode 189. Rotate Array
- 189. Rotate Array LeetCode
- [LeetCode]189. Rotate Array
- leetcode-189.-Rotate Array
- LeetCode 189. Rotate Array
- leetcode 189. Rotate Array
- LeetCode *** 189. Rotate Array
- [LeetCode]189. Rotate Array
- LeetCode 189. Rotate Array
- leetcode-189. Rotate Array
- Leetcode 189. Rotate Array
- leetcode 189. Rotate Array
- Java学习总结--初始化块
- Quartz2D绘图相关方法
- cookie和session的区别
- 周期字符串的最小周期
- java反射机制的应用
- leetcode-189.-Rotate Array
- 单例模式——之饿汉模式
- Spring JdbcTemplate API
- 14. Spring国际化与图片验证码
- 278. First Bad Version
- vi 技巧和诀窍:令人刮目相看的 10 个超酷命令
- 集合运算(标准差)
- linux常用命令
- 自定义View绘制心得(自定义view和自定义viewGroup)