[leetcode][array] Rotate Array
来源:互联网 发布:淘宝会员名取什么好 编辑:程序博客网 时间:2024/05/16 11:32
题目;
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.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
方法一:class Solution {public://最直观的解法:循环移动k次,每次移动n个元素 O(n*k) 超时void rotate(vector<int>& nums, int k) {if (nums.size() <= 1) return;int n = nums.size();k = k%n;for (int i = 0; i < k; ++i){int cur = nums[n - 1];//暂存最后一个元素for (int j = n - 1; j > 0; --j){nums[j] = nums[j - 1];}nums[0] = cur;}}};
方法二:
class Solution {public://时间复杂度O(n),空间复杂度O(k)void rotate(vector<int>& nums, int k) {if (nums.size() <= 1) return;int n = nums.size();k = k%n;//暂存后半部分vector<int> tmp(nums.end() - k, nums.end());//前半部分整体后移k步for (int i = n - 1; i >= k; --i){nums[i] = nums[i - k];}//将暂存的后半部分放入前半部分for (int i = 0; i < k; ++i){nums[i] = tmp[i];}}};
注:本方法还可以做一下空间的优化:不一定暂存后半部分,可以暂存元素较少的那一部分。
方法三:
class Solution {public://先分别反转前后两部分,然后反转整个数组 时间复杂度O(n),空间复杂度O(1)void rotate(vector<int>& nums, int k) {if (nums.size() <= 1) return;int n = nums.size();k = k%n;reverse(nums.begin(), nums.end() - k);reverse(nums.end() - k, nums.end());reverse(nums.begin(), nums.end());}};
0 0
- [leetcode][array] Rotate Array
- Leetcode - Array - 189. Rotate Array
- 189. Rotate Array leetcode(array)
- LeetCode-Array-189. Rotate Array
- 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
- mysql sql语句大全
- java第三次作业:网络编程
- 第十一周 项目二--职员有薪水了(1)
- 遗传算法Java实现以及TSP问题遗传算法求解
- rust 整数加减乘除
- [leetcode][array] Rotate Array
- ListView 中使用onItemClick和onItemLongClick的常见问题
- java之缓冲池
- [Python]程序性能分析
- Android客户端通过socket与服务器通信
- 第十二周项目二 摩托车继承自行车和机动车
- 网页版贪吃蛇
- VIM 的移动
- WPF Timer替代者