Rotate Array
来源:互联网 发布:网络被攻击 编辑:程序博客网 时间:2024/05/18 00:54
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
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
class Solution {public: void rotate(int nums[], int n, int k) { if(nums==NULL) { return ; } if(n<=0 || k<0) { return ; } k=k%n; int nBegin=0; int nEnd=n-1; while(nBegin<nEnd) { int nTemp=nums[nBegin]; nums[nBegin]=nums[nEnd]; nums[nEnd]=nTemp; ++nBegin; --nEnd; } nBegin=0; nEnd=k-1; while(nBegin<nEnd) { int nTemp=nums[nBegin]; nums[nBegin]=nums[nEnd]; nums[nEnd]=nTemp; ++nBegin; --nEnd; } nBegin=k; nEnd=n-1; while(nBegin<nEnd) { int nTemp=nums[nBegin]; nums[nBegin]=nums[nEnd]; nums[nEnd]=nTemp; ++nBegin; --nEnd; } }};
0 0
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- rotate array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- 黑马程序员——java基础学习笔记——第五天
- 黑马程序员——java基础——异常
- 基于 spring4 java config(配置)的servlet3 文件上传于下载
- 欢迎使用CSDN-markdown编辑器
- Valid Parentheses
- Rotate Array
- JStorm之Topology调度
- 一个球从100米高的自由落下,每次落地后反跳回原高度的一半,再落下,再反弹。求第 10次落地时,共经过多少米,第10次反弹多高。
- Path Sum
- 二叉排序树的一些简单操作
- 欢迎使用CSDN-markdown编辑器
- Minimum Depth of Binary Tree
- 策略模式
- Swift版的SQLite帮助类