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

Challenge:

Either of the following solutions are acceptable:

O(n) Space, O(nlogn) Time

O(n) Space, O(n) Time

Example:

numbers=[2, 7, 11, 15], target=9

return [1, 2]

Solution:

O(n) Space, O(n) Time: This could be done by using an HashMap. We put all the numbers into the HashMap first. Then, we search for the target - nums[i] from the HashMap.

O(n) Space, O(nlogn) Time: Sort the array first. Then, we need to use two pointer from left and right. If the sum of these two numbers is too large, decrease right; if the sum of these two numbers is too small, increase left.

Code:

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] nums, int target) {
        if (nums == null) {
            return new int[] {};
        }
        //key is complement of i-th number, value is the index i.
        HashMap<Integer, Integer> hmap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hmap.containsKey(nums[i])) {
                //output is non-zero based.
                return new int[] {hmap.get(nums[i]) + 1, i + 1};
            } else {
                hmap.put(target - nums[i], i);
            }
        }
        return new int[] {-1, -1};
    }
}

results matching ""

    No results matching ""