189. Rotate Array
来源:互联网 发布:json 汉字编码 编辑:程序博客网 时间:2024/05/16 05:43
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]
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析:
根据编程珠玑入门,对数组A旋转前i个数,可以换个理解方式将A看作ab.
其中a是前i个数,b是剩下的数,等效为(ab)转换为ba.((a)'(b)')'=ba。因此将a先翻转,再将b翻转,最后将前两部结果翻转即可以得到ba。
代码:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int t=k%nums.size();
int n=nums.size();
if(t>0)
{
int left=0;
int right=n-t-1;
while(left<right)
swap(nums[left++],nums[right--]);
left=n-t;right=n-1;
while(left<right)
swap(nums[left++],nums[right--]);
left=0;right=n-1;
while(left<right)
{swap(nums[left++],nums[right--]);}
}
}
};
- Leetcode - Array - 189. Rotate Array
- 189. Rotate Array leetcode(array)
- LeetCode-Array-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
- 189. Rotate Array LeetCode
- 189. Rotate Array
- [LeetCode]189. Rotate Array
- 189. Rotate Array
- leetcode-189.-Rotate Array
- 189. Rotate Array
- 189. Rotate Array
- 189. Rotate Array
- React Native 环境配置
- Jenkins快速上手
- 双网卡实现负载均衡技术的实现与原理
- Thrift开发示例
- android开发之网络请求框架比较
- 189. Rotate Array
- 码农小汪-struts2学习2-Structs2简单使用流程
- fstream的基础用法
- Android-解决顶部Menu那三点不显示的问题
- linux查看磁盘io的几种方法
- 无法在节点上执行物理内存检查
- 27.Material Design详解
- 模板方法模式与策略模式的区别
- Android Ultra PullToRefresh的使用和简单定制