第二周LeetCode
来源:互联网 发布:ug电极自动编程 编辑:程序博客网 时间:2024/06/05 08:57
Rotate Array
题目
难度 Easy
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.
实现思路
这次题目利用了stl模板的便利,代码比较短,每次就是把尾部的元素pop掉,然后插入到头部。复杂度为k乘以vector的insert算法的复杂度(即O(n),因为k比n小,所以复杂度为O(n)。同样的思路可以用栈和链表做,没有限定参数列表的话,链表的复杂度最低,因为pop_ back()和push_front()的复杂度都为O(1)。
代码
void rotate(vector<int>& nums, int k) { int temp; for (int i = 0; i < k; i++) { temp = *(nums.rbegin()); nums.pop_back(); auto it = nums.begin(); nums.insert(it, temp); } }//若用链表void rotate(list<int> &nums, int k) { int temp ; for (int i = 0; i < k; i++) { temp = nums.back(); nums.pop_back(); nums.push_front(temp); } }
阅读全文
0 0
- leetcode-python 第二周
- leetcode-第二周
- 第二周leetcode水题
- 第二周LeetCode
- LeetCode题解 第二周
- [leetcode] 第二周作业
- 第二周LeetCode算法题
- LeetCode 算法习题 第二周
- 第二周:[LeetCode]169. Majority Element
- 第二周:[LeetCode]53. Maximum Subarray
- 【leetcode】第二题
- leetCode OJ 第二题
- leetcode第二题
- LeetCode第二天
- leetcode算法第二题
- LeetCode第二天
- leetcode第二题AddTwoNumber
- java and python学习——第二周leetcode刷题
- Html 浮动
- Tensorflow-线性回归
- 横滑菜单和侧拉菜单
- [BZOJ]4974: 字符串大师 KMP
- codevs 1020 孪生蜘蛛 floyd 解题报告
- 第二周LeetCode
- 业务逻辑
- SourceTree使用介绍
- RXJava详解
- ios-Swift处理异常的三种方式
- 星际争霸:登录韩服等其他国家服务器
- BZOJ 4817 [LCT][线段树][树链剖分]
- [BZOJ1006]神奇的国度(完美消除序列)
- [NLP]论文笔记-A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SENTENCE EMBEDDINGS