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),是基本的牺牲空间来提升效率的方式。

猜你喜欢

转载自plan454.iteye.com/blog/2184725
今日推荐