Wednesday, February 3, 2016

[LeetCode] 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

Method 1: Hash Map.
Time: O(n)
Space: O(n)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        int[] res = new int[2];
        
        if(0 == len)
            return res;
            
        Map m= new HashMap();
        for(int i = 0; i < len; ++i){
            if(m.containsKey(target - nums[i])){
               res[0] = m.get(target - nums[i])+1;
               res[1] = i+1;
            }
             m.put(nums[i], i);
        }
        return res;
    }
}
Method 2: Sort, then use two pointers.

Time: O(nlogn)
Space: O(n), we need new objects to keep the index. Or we don't keep the index, but scan the array twice.


import java.util.*;

class pair{
    public int index;
    public int val;
    pair(int index, int val){
        this.index = index;
        this.val = val;
    }
}

public class TwoSum{
    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        int[] res = new int[2];
        if(0 == len)
            return res;
            
        pair[] pArr = new pair[len];
        for(int i = 0; i < len; ++i){
            pArr[i] = new pair(i, nums[i]);
        }
        Arrays.sort(pArr, new Comparator()
                {
                public int compare(pair A, pair B){
                    return A.val - B.val;
                    }
                }
        );

        int i = 0;
        int j = len -1;
        while(i < j){
            if (pArr[i].val + pArr[j].val == target){
                res[0] = Math.min(pArr[i].index+1, pArr[j].index+1);
                res[1] = Math.max(pArr[i].index+1, pArr[j].index+1);
                return res;
            }
            else if ( pArr[i].val + pArr[j].val < target){
                ++i;
            }
            else{
                --j;
            }
        }
        return res;
    }

    public static void main(String[] args){
        TwoSum t = new TwoSum();
        int[] nums = new int[]{3, 2, 4};
        System.out.println(Arrays.toString(t.twoSum(nums, 6)));
    }
}

No comments:

Post a Comment