[LeetCode] Two Sum

Problem

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Solution

Brute Force

The simpleset solution. Just iterate two times to find the target numbers

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        // In case there is no solution, we'll just return null
        return null;
    }
}

Use HashTable

To improve complexity, we need more efficient way to check if the complement exists in the array. For just one iteration, check if there is target - nums[i] as key in the map. If exists, that means i and target-nums[i] index is the pairs of two integer that sum equals to target

  • Hash Table benefits because, it allows fast lookup in near constant time
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<nums.length; i++) {
            if(map.containsKey(target - nums[i]))
                return new int[] {map.get(target - nums[i]), i};
            map.put(nums[i], i);
        }
        return null;
    }
}