LeetCode:Rotate Array
来源:互联网 发布:免费直播软件 编辑:程序博客网 时间:2024/05/21 22:56
问题描述:
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.
思路:
方法一:使用O(K)个空间,复杂度为O(n),将后半段保存在数组中,然后将前半段后移,切记:是倒着移动!
方法二:使用O(N)个空间,复杂度为O(n),将前后半段分别存储,代码略。
代码:
public: void rotate(vector<int>& nums, int k) { int n = nums.size(); if(k == 0) { return; } else if(k > 0) { k = k % n; int array[k]; for(int i = n - k,j = 0; i < n; ++ i,++ j) array[j] = nums[i]; for(int i = n - k -1,j = n - 1; i >= 0; --i,--j) nums[j] = nums[i]; for(int i = 0,j = 0; i < k; ++i,++j) nums[i] = array[j]; } else { k = k % n ; k = n + k; int array[k]; for(int i = n - k,j = 0; i < n; ++ i,++ j) array[j] = nums[i]; for(int i = n - k -1,j = n - 1; i >= 0; --i,--j) nums[j] = nums[i]; for(int i = 0,j = 0; i < k; ++i,++j) nums[i] = array[j]; } }};</span>
1 0
- [leetcode][array] Rotate Array
- LeetCode[Array]: Rotate Image
- LeetCode:Rotate Array
- [LeetCode] Rotate Array
- *LeetCode-Rotate Array
- [LeetCode]189.Rotate Array
- Rotate Array - LeetCode - Java
- Rotate Array--Leetcode(Java)
- Leetcode--Rotate Array
- LeetCode: Rotate Array
- LeetCode Rotate Array
- Rotate Array(leetcode)
- leetcode Rotate Array
- Leetcode: Rotate Array
- [Leetcode]11 Rotate Array
- [LeetCode][189][Rotate Array]
- Leetcode:Rotate Array
- LeetCode: Rotate Array
- 2015 长春、沈阳区域赛总结
- 解决MAC ssh本地断开后启动的服务会停止的问题
- switch跳转表分析
- 通知——Notification
- 10003---使用jQuery实现Ajax
- LeetCode:Rotate Array
- Effective Objective-C 2.0 第11条:理解objc_msgSend的作用
- 文件加密程序
- Hql使用总结
- geohash实现(c语言)
- 图片降噪
- C 判断socket 是否已经断开
- 深入理解Java参数传递
- Android LruCache类分析