Sunday, February 1, 2015

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
Solution1: brute force
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        
        for(int i = 0; i < numbers.length; i++) {
            for(int j = i + 1; j < numbers.length; j++) {
                if(numbers[i] + numbers[j] == target) {
                    res[0] = i + 1;
                    res[1] = j + 1;
                }
            }
        }
        return res;
    }
}
Solution2:  HashMap
Time complexity depends on the put and get operations of HashMap which is normally O(1).
O(n) runtime, O(n) space.
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        HashMap map = new HashMap();
        
        for(int i = 0; i < numbers.length; i++) {
            if(map.containsKey(target-numbers[i])) {
                res[0] = map.get(target - numbers[i]) + 1;
                res[1] = i + 1;
            }else {
                map.put(numbers[i], i);
            }
        }
        return res;
    }
}
Solution3:  
先对数组进行排序,然后使用夹逼的方法找出满足条件的pair. 
算法的时间复杂度是O(nlogn+n)=O(nlogn),空间复杂度取决于排序算法。
注意输出结果改成了满足相加等于target的两个数,而不是他们的index。因为要排序,如果要输出index,需要对原来的数的index进行记录,方法是构造一个数据结构,包含数字的值和index,然后排序。
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        
        Arrays.sort(numbers);
        int l = 0, r = numbers.length - 1;
        while(l < r) {
            if(numbers[l] + numbers[r] == target) {
                res[0] = numbers[l];
                res[1] = numbers[r];
                return res;
            }else if(numbers[l] + numbers[r] > target) {
                r--;
            }else {
                l++;
            }
        }
        return null;
    }
}

No comments:

Post a Comment