[LeetCode] Rotate Array
2015-07-17 07:04
369 查看
This problem, as stated in the problem statement, has a lot of solutions. Since the problem requires us to solve it in O(1) space complexity, I only show some of them in the following.
The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.
The second one is to use swap, and is translated from the C code in this link.
For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).
The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.
class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k %= n; reverse(nums.begin(), nums.begin() + n - k); reverse(nums.end() - k, nums.end()); reverse(nums.begin(), nums.end()); } };
The second one is to use swap, and is translated from the C code in this link.
class Solution { public: void rotate(vector<int>& nums, int k) { int start = 0, n = nums.size(); for (; k %= n; n -= k, start += k) for (int i = 0; i < k; i++) swap(nums[start + i], nums[start + n - k + i]); } };
For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).
相关文章推荐
- 要画sequence diagram 请记得Astah Community 7.0.0/846701
- 一个Linux内核的自旋锁设计-接力嵌套堆栈式自旋锁
- 一个Linux内核的自旋锁设计-接力嵌套堆栈式自旋锁
- [CareerCup] 1.8 String Rotation 字符串的旋转
- Vim 常用快捷键
- SDWebImage使用入门
- 【Hibernate二】对象的状态
- C++ 类初探
- pat 1001. A+B Format (20)
- 【LeetCode-面试算法经典-Java实现】【005-Longest Palindromic Substring(最长回文子串)】
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 算法分析与设计实验四 密码算法
- 【LeetCode-面试算法经典-Java实现】【003-Longest Substring Without Repeating Characters(最长非重复子字符串)】
- 深入浅出数据分析(一)——MySQL+EXCEL+R统计问卷调查
- First Bad Version
- tar: Exiting with failure status due to previous errors
- [CareerCup] 1.7 Set Matrix Zeroes 矩阵赋零
- eclipse maven plugin 插件 安装 和 配置
- maven安装步骤
- 237 - Delete Node in a Linked List