34.Rotate Array
2015-10-21 10:31
127 查看
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
rotated to
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
分析:在开始做的时候我用的是list来存。提交之后提示运行超时:
之后,我改变成map之后存储,(与list的思路完全一样),提交之后通过。leetcode显示的运行时间是9ms。
第三种方法,用System.arraycopy方法做。提交之后通过,运行时间是0ms。
通过做这道题目,深刻了解了map要比list的查询效率高很多,还有就是java自带的一些方法很强大。
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); } }
第三种方法,用System.arraycopy方法做。提交之后通过,运行时间是0ms。
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自带的一些方法很强大。
相关文章推荐
- Instant Client Downloads for Linux x86
- Java 代理,动态代理
- 获取IE下载历史的具体实现
- 修改placeholder文字颜色
- 你不知道的JavaScript--Item13 理解 prototype, getPrototypeOf 和__proto__
- poj2486 Apple Tree 树形DP
- [leetcode]#160 Intersection of Two Linked Lists
- css有趣的转换(初学)
- Tomcat启动超时问题Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds
- 美好的大一
- 你不知道的JavaScript--Item13 理解 prototype, getPrototypeOf 和__proto__
- shell实践(一)读取一个文件输出文件内容
- Android——ListView实现简单列表
- MyBatis学习总结(一)——MyBatis快速入门
- 基本数据类型数据对象包装类 小结
- Android——ListView实现简单列表
- tcp的关闭(shutdonw、close、SO_LINGER选项)与 连接断开情形判断
- 跟我学Guava:基础1.2-前置条件
- android 请求服务器,json解析
- ecplise新建项目push到git