Rotate Array
来源:互联网 发布:软件安装文档模板 编辑:程序博客网 时间:2024/05/21 09:22
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.
题意是翻转数组,用尽可能多的方法
第一种
从n - k + 1 处依次循环右移k次,效率底,代码简单。
第二种
重新开辟一个新数组,缺点是需要n个额外空间
第三种
开一条链,利用链表翻转,耗费空间
第四种
1、将0,n - k - 1 和n - k ,n - 1分别翻转
2、将0,n - 1翻转
public class Solution { public void rotate(int[] nums, int k) { k = k % nums.length;//旋转nums.length没有意义 if(k <= 0){//参数不合适 return ; } int n = nums.length; reverse(nums, 0, n-k-1); reverse(nums, n-k, nums.length-1); reverse(nums, 0, nums.length-1); } private void reverse(int[] nums, int start, int end){ while(start<end){ int tmp=nums[start]; nums[start]=nums[end]; nums[end]=tmp; start++; end--; } }}
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
- OpenGL学习笔记之配置OpenGL
- 数据结构中的栈
- 对左值和右值的理解
- 把一个十进制的数转换成为16进制的数
- Android开发,开源项目SlidingMenu的导入
- Rotate Array
- 一年之计在于春-2015年两会-国家总理李克强答记者问
- 定义多线程任务
- 同步传输和异步传输有什么区别?
- UVAL 3486 Cells DFS时间戳
- 测试Service
- 从Free到Page Cache
- 蓝桥杯2015培训笔记(1)
- 蓝桥杯2015培训笔记(2)