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


題意:給一個數組,要求返回其中兩個相加能獲得目標值的數的序號。要求序號小的放在前面,且能夠保證必須有解。

思路:先排序,從兩端向中間遍歷,若是兩數之和大於目標則終點指針左移,不然起點指針右移,直到等於目標數。查找算法複雜度爲n,排序複雜度爲nlogn,因此算法複雜度爲nlogn

實現:java

import java.util.*;
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] t=new int[2];
          ArrayList<Node> l=new ArrayList<Node>();
          for(int i=0;i<numbers.length;i++){
               l.add(new Node(i,numbers[i]));
          }
          l.sort(new Comparator<Node>(){

               @Override
               public int compare(Node arg0, Node arg1) {
                    return arg0.value-arg1.value;
               }
              
          });
          for(int s=0,e=numbers.length-1;s<e;){
               if(l.get(s).value+l.get(e).value==target){
                    if(l.get(s).index<l.get(e).index){
                         t[0]=l.get(s).index;
                         t[1]=l.get(e).index;
                    }else{
                         t[1]=l.get(s).index;
                         t[0]=l.get(e).index;
                    }
                    return t;
               }else if(l.get(s).value+l.get(e).value<target){
                    s++;
               }else{
                    e--;
               }
          }
          return t;
    }
}
class Node{
     int index;
     int value;
     public Node(int index, int value) {
          super();
          this.index = index+1;
          this.value = value;
     }
    
}
相關文章
相關標籤/搜索