Two Sum
来源:互联网 发布:js date对象 编辑:程序博客网 时间:2024/05/17 12:56
最近准备面试刷leetcode沉淀沉淀算法
第一题看着不难,分析了一下用冒泡搞定了,然而运行时间大比分落后让我很郁闷,寻思改进,查了挺多资料,总结了一下,由于我的主语言是java所以用java编写
思路一:
利用基于冒泡排序的嵌套循环的方式两两相加
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
int[] a = new int[2];
for(int i=0;i < length;i++){
for(int j=i+1;j < length;j++){
if(i != j && nums[i]+nums[j]== target){
if(i>j){
a[0]= j;
a[1]=i;
}else{
a[0]= i;
a[1]=j;
}
}
}
}
return a;
}
}
赋值部分冗余是用空间换时间的解决方案,使用Math函数也可以做但消耗时间更多,我这个方案最终耗时92ms
方案二
参考其他人的思路,原理是复制数组排序,然后采用首尾游标方式求和判断,目标大高位减,目标小低位加,从而获得正确结果
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
int[] result = {0,1};
int[] copyArray = new int[length];
if(nums==null||length<2) return result; System.arraycopy(nums,0,copyArray,0,length); Arrays.sort(copyArray); int low=0,high = length-1; boolean flag = true; while(low<high){ if(copyArray[low]+copyArray[high]<target){ low++; } else if(copyArray[low]+copyArray[high]>target){ high--; } else{ break; } } for(int i=0;i<length;i++){ if(nums[i] == copyArray[low] && flag==true){ result[0] = i; flag = false; continue; } if(nums[i] == copyArray[high]){ result[1] = i; continue; } } if(result[0]>result[1]){ int temp = result[0]; result[0] = result[1]; result[1] = temp; } return result;}这样一来,计算时间变成了6ms消耗时间变成原来的十五分之一,然而体积也大了,但是目前来说没找到更好的改进方案,且时间超过了峰值所以准备做第二题了。
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 正则表达式30分钟入门教程
- 指针和引用的区别
- Webpack学习笔记与填坑记录
- C#、VS2012 Winform程序解决方案名称更改后报错“调试器无法继续运行该进程。调用的目标发生了异常。”
- JS中的异步,以及如何异步
- Two Sum
- 堆排序 Java
- 类对象结构
- Composer实现PHP中类的自动加载
- 秦始皇修路,白书P345LA5713(最小生成树,Kruskal算法)
- linux内核kmalloc函数使用方法
- sci期刊发表医学论文注意哪些事项
- springmvc- 分页插件-<jsp:include >遇到问题
- make 2>&1 | tee make.out 命令解释