`
plan454
  • 浏览: 7008 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

two sum

阅读更多
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

可以用一个暴力的方式,用嵌套的FOR循环 O(N^2)
       for(int i = 0;i<numbers.length;i++){
       for(int j = i;j<numbers.length;j++){
         if(numbers[i]+numbers[j]==target&&i != j){
                  return new int[]{i+1,j+1};
             }
       }
    }
      return null;
但是这个没有用,时间太长了不通过。
可以不用这种时间复杂度高的,可以自己定义一个类,来进行运算。但是更取巧的一个方法是可以通过hashmap进行一个解决,具体代码如下
int [] result = new int[2];
    HashMap<Integer,Integer> a = new HashMap<Integer,Integer>();
    for(int i = 0;i<numbers.length;i++){
    if(a.get(target - numbers[i])!= null){
    result[0] = i+1<a.get(target - numbers[i])?i+1:a.get(target - numbers[i]);
    result[1] = i+1>a.get(target - numbers[i])?i+1:a.get(target - numbers[i]);
   
    }else{
    a.put(numbers[i], i+1);
    }
    }
   
   
    
        return result;
时间复杂度为O(nLOGn),是基本的牺牲空间来提升效率的方式。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics