rotate array
2016-03-28 13:27
453 查看
leetcode试题如下:
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
rotated to
很简单的一道题,本来我自己想的是将数组复制然后在进行处理(具体的代码就不在赘述,实在是无颜见人,时间复杂度为O(n),只是在测试的时候发现runtime只是胜过了11.7%的人,以我的水平估计并没能优化。
然后在Discuss中发现简单并且优雅的算法,其时间复杂度为o(n)其空间复杂度为o(1),备受启发,特将java版本贴出来:
public class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
k=k%length; // 这里他可能给出的k>length所以要特别处理一下
this.reverse(nums, 0, length-k-1);
this.reverse(nums, length-k, length-1);
this.reverse(nums, 0, length-1);
}
public void reverse(int[] nums, int l, int r){
while (l < r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
}
这个程序的思路相当不错,大概为三个步骤:
Step 1 - 12345 6789 ---> 54321 6789
Step 2 - 54321 6789 ---> 54321 9876
Step 3 - 543219876 ---> 678912345
然而我测试的结果依然只是1ms和我的写法是一样的依然只战胜了11.7%的人,囧。
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].
很简单的一道题,本来我自己想的是将数组复制然后在进行处理(具体的代码就不在赘述,实在是无颜见人,时间复杂度为O(n),只是在测试的时候发现runtime只是胜过了11.7%的人,以我的水平估计并没能优化。
然后在Discuss中发现简单并且优雅的算法,其时间复杂度为o(n)其空间复杂度为o(1),备受启发,特将java版本贴出来:
public class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
k=k%length; // 这里他可能给出的k>length所以要特别处理一下
this.reverse(nums, 0, length-k-1);
this.reverse(nums, length-k, length-1);
this.reverse(nums, 0, length-1);
}
public void reverse(int[] nums, int l, int r){
while (l < r) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
}
这个程序的思路相当不错,大概为三个步骤:
Step 1 - 12345 6789 ---> 54321 6789
Step 2 - 54321 6789 ---> 54321 9876
Step 3 - 543219876 ---> 678912345
然而我测试的结果依然只是1ms和我的写法是一样的依然只战胜了11.7%的人,囧。
相关文章推荐
- 三月随想
- I/O流<二>
- DOM与jquery的区分(一:元素节点与属性)
- Easyx库-贪吃蛇小游戏
- 黑马程序猿——Java中的类载入器
- ThermalLabel SDK for .NET使用教程:创建与打印条形码
- bootstrapValidator如何重新初始化
- AndroidStudio环境搭建流程
- 关于OC中的Block,Swift中的闭包,C++11中的lambda表达式等匿名函数详解
- 作业4(必做2)----指定词频统计
- hdu 1711 Number Sequence KMP模板题
- 设备上下文的属性及其相关函数
- arm7tdmi的i2c驱动注释
- cbc公司笔试题
- BCD和HEX转换程序
- 项目组人员培训 - 项目管理系列文章
- leetcode 48. Rotate Image
- platform驱动之probe函数
- 透明状态栏和透明导航栏
- 写了几年代码了,苦苦追寻,应该沉淀下来了,好好研究。net底层框架,以及较好的分层框架