34.Rotate Array
来源:互联网 发布:最近微信网络不稳定 编辑:程序博客网 时间:2024/06/14 11:28
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.
分析:在开始做的时候我用的是list来存。提交之后提示运行超时:
public void rotate(int[] nums, int k) { //提交之后说运行超时 int len = nums.length; LinkedList<Integer> list = new LinkedList(); int i=0; for(i=0;i<len;i++){ list.add(nums[i]); } for(i=0;i<len;i++){ int index = (i+k)%len; nums[index] = list.get(i); } }
之后,我改变成map之后存储,(与list的思路完全一样),提交之后通过。leetcode显示的运行时间是9ms。
public void rotate3(int[] nums, int k) { int len = nums.length; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int i=0; for(i=0;i<len;i++){ map.put(i, nums[i]); } for(i=0;i<map.size();i++){ int index = (i+k)%len; nums[i]=map.get(index); } }
public void rotate4(int[] nums, int k) { int len = nums.length;if(len<=1){return;}int temp[] = new int[k];k=k%len;System.arraycopy(nums, len-k, temp, 0, k);System.arraycopy(nums, 0, nums, k, len-k);System.arraycopy(temp, 0, nums, 0, k);}
通过做这道题目,深刻了解了map要比list的查询效率高很多,还有就是java自带的一些方法很强大。
0 0
- 34.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
- 一个简单的JavaScript函数式编程教程
- ZooKeeper系列之八:ZooKeeper的简单操作
- mac securecrt无法记住密码的解决方法
- hdu5451 矩阵乘法+斐波那契 + 循环节
- 重新理解Java的抽象类和接口
- 34.Rotate Array
- 获取当前目录
- Android中的drawable下的资源使用
- 线性方程组(A是上三角矩阵时)的C++求解
- js-预编译就是那个鬼
- HDU - 1540 Tunnel Warfare(线段树 区间合并)
- QT事件--阐述的比较系统
- [架构师]我要怎么做才能成为一名架构师
- Ubuntu 上文件共享