Monday, January 4, 2016

[LeetCode] 1. Two Sum [Private]

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(1)

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;
    }
}

Bad:
Keep all elements, then go through it again. Result in complicated condition for equal number judgement.
But might works better when the exact one condition is relax. 
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(nums[i])){
                m.put(nums[i], m.get(nums[i])+1);
            }
            else{
                m.put(nums[i], 1);
            }
        }
        
        for(int i = 0; i < len; ++i){
            int x = nums[i];
            int y = target - x;
            if(x == y && m.get(x) < 2)
                continue;
            if(m.containsKey(y)){
                int index = 0;
                for(int j = 0; j < len; ++j){
                    if (nums[j] == x || nums[j] == y) res[index++] = j+1;
                    if(3 == index)
                        return res;
                }
            }
        }
        return res;
    }
}

No comments:

Post a Comment