189 - rotate array
来源:互联网 发布:物联网与java 编辑:程序博客网 时间:2024/06/08 18:45
题目
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].
Could you do it in-place with O(1) extra space?
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].
Could you do it in-place with O(1) extra space?
方案1:
首先分别翻转前n-k个元素组和后k个元素组,再整体翻转一次;
注意:题目没限制k一定小于n,所以要用k=k%n;来防止越界。
该方案空间复杂度O(1),但是时间复杂度线性,代码如下:
class Solution {public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k = k%n; for( int i=0,j=n-k-1; i<j; ++i,--j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } for( int i=n-k,j=n-1; i<j; ++i,--j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } for( int i=0,j=n-1; i<j; ++i,--j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }};
0 0
- [LeetCode][189][Rotate Array]
- Leetcode 189: Rotate Array
- leetCode #189 Rotate Array
- LeetCode #189 Rotate Array
- 189Rotate 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-189 Rotate Array
- #189 Rotate Array
- Leetcode[189]-Rotate Array
- leetcode[189]:Rotate Array
- 189Rotate Array
- leetcode 189: Rotate Array
- 【LeetCode】127. Word Ladder
- wait notify notifyall synchronized
- MFC----文档 视图 框架窗口间的关系 和消息传送规律
- 欢迎使用CSDN-markdown编辑器
- 今日头条新闻采集爬虫分享
- 189 - rotate array
- 13章上机练习
- C++ STL <vector>
- HDU 5874-Friends and Enemies(n个结点的无三元环的图的最大边数)
- MapReducer工作流程小结
- 51Nod - Nim游戏(博弈)
- Java大牛养成记(11)----Struts 2 & Struts 1
- 实现顺序栈各种基本运算算法
- JavaScript中的window.parent ,window.top,window.self 等等