Search This Blog

Friday, December 28, 2012

LeetCode:Two Sum

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
Idea: Sort the array while keeping track of the indices. Then use two pointers at the head and tail to search for the solution in linear time. Overall time is O(nlogn).


public class Solution {
    
    public class Element{
        int val;
        int index;
        Element(int val, int index){
            this.val=val;
            this.index=index;
        }
    }
    
    public int[] twoSum(int[] numbers, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Element[] e = new Element[numbers.length];
        for(int i=0;i<numbers.length;i++){
            e[i]=new Element(numbers[i],i);
        }
        Arrays.sort(e, new Comparator<Element>(){public int compare(Element a, Element b){ return a.val>b.val?1:(a.val==b.val?0:-1);}});
        
        int i=0,j=numbers.length-1;
        int[] res = new int[2];
        while(i<j){
            int temp = e[i].val+e[j].val;
            if(temp==target){
                res[0]=Math.min(e[i].index,e[j].index)+1;
                res[1]=Math.max(e[i].index,e[j].index)+1;
                return res;
            }else if(temp>target)
                j--;
            else
                i++;
        }
        return res;
    }
}

1 comment:

Anonymous said...

水印大哥 你在哪高就啊!~你这题写的很精妙啊! 我都理解不了啊!~高手高手