[leetcode 189] Rotate Array
来源:互联网 发布:桥林中学的网络 编辑:程序博客网 时间:2024/04/29 21:04
Quesiton:
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]
.
题目要求将长度为n的数据向后移动k步,可知当k=n时,移动后的数据与原数据相同;
当k<n时,先将数据序列的最后k个单独存到一个数组中,然后循环一次将数据序列整体移动k步,最后将k个数据的数组依次赋值到原数组的前k个位置中。
代码如下:
<span style="font-size:14px;">class Solution {public: void rotate(vector<int>& nums, int k) { vector<int> n(k); int len = nums.size(); while(len <= k) k -= len; for(int i = 0; i < k; ++i){ n[i] = nums[nums.size()-k+i]; } for(int j = nums.size()-1; j > k-1 ; --j){ nums[j] = nums[j-k]; } for(int i = 0; i < k; ++i){ nums[i] = n[i]; } }};</span>
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
- 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】189Rotate Array
- LeetCode 189 Rotate Array
- Linux中posix消息队列系统函数mq_timedreceive()谨慎使用
- Context 之 内核剖析 读笔
- uva 10771——Barbarian tribes
- UILabel的自适应长度
- java 网络编程
- [leetcode 189] Rotate Array
- 为Python安装easy_install工具
- Android View中onSave(),onRestore(),getWidth(),getMeasureWidth()方法解析
- VS2012其中的一个小BUG
- Docker核心技术
- 邮局选址问题
- JNI学习笔记
- iOS 计算某个时间到现在是多少月/天/时的代码
- Mac上OpenFire启动失败解决方案