首页 > 其他 > 详细

Leecode#1

时间:2015-10-09 00:34:20      阅读:260      评论:0      收藏:0      [点我收藏+]

原始算法:

  for(int index1 = 0; index1 < nums.length; index1++)

    for(int index2 = index1 + 1; index2 < nums.length; index2++)

      if((nums[index1]+nums[index2])==target){

    }

  这个算法时间复杂度就是到O2

 

 

 

典型的空间换时间

优化算法:

public class Solution {
public int[] twoSum(int[] nums, int target) {

int[] results = new int[2];
results[0] = -1;
results[1] = -1;

final HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();


for(int i = 0; i < nums.length; i++){
if(hm.containsKey(target - nums[i])){
int index = hm.get(target - nums[i]) + 1;
results[0] = Math.min(index,i+1);
results[1] = Math.max(index,i+1);
}
hm.put(nums[i], i);
}
return results;
}
}

Leecode#1

原文:http://www.cnblogs.com/horseLing/p/4862696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!