LeetCode 189. Rotate Array
来源:互联网 发布:拍慢动作视频软件 编辑:程序博客网 时间:2024/05/21 10:10
Description
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]
.
Analysis
本题即循环右移。要记得将移位数k
对n
取余,即
否则会多作无用功。
解法一:新建
vector<int> result[n]
,按右移后顺序填充数组,再赋给nums
。 解法二:本地插入删除,将
nums[n-k]~nums[n-1]
的所有元素,插入到nums
开头,然后删除最后的歌k
个元素。Code
Version 1
class Solution {public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k %= n; vector<int> result(n); int i = 0; int j = n - k; while (j < n) result[i++] = nums[j++]; j = 0; while (i < n) result[i++] = nums[j++]; nums = result; }};
Version 2
class Solution {public: void rotate(vector<int>& nums, int k) { k %= nums.size(); nums.insert(nums.begin(), nums.end() - k, nums.end()); nums.erase(nums.end() - k, nums.end()); }};
Appendix
- Link: https://leetcode.com/problems/rotate-array/
- Run Time:
- Version 1: 22ms
- Version 2: 23ms
- My first submission in Discussion…
Link: https://discuss.leetcode.com/topic/85266/3-line-c-solution-using-insert-and-erase
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
- 189. Rotate Array LeetCode
- [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
- Java知识图谱(附:阿里Java学习计划)
- 微服务架构(七): 服务发现与服务注册
- 计算几何模板
- strlen高效实现
- ngrok配置微信公众号本地开发环境
- LeetCode 189. Rotate Array
- Swift3.0 /Swift2.3——dispatch_group的使用
- 集合框架
- UVA 11978 / Lightoj 1358 圆与简单多边形交的面积
- nodejs-express frontend project
- <a>标签<form>标签
- sqlite锁机制概述
- LeetCode-Easy部分标签为LinkedList 237. Delete Node in a Linked List
- Java集合---LinkedList源码解析