Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have _exactly _one solution, and you may not use the _same _element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Analysis

经典题,但是要注意的是不能重用同一个元素,一个常见错误在于先遍历一遍生成一个hashmap(nums[i], i),再遍历一般寻找target - nums[j]是否存在,这样就可能重复用到同一个元素导致错误。比如

Input:

[3,3]
6

Expected:

[0,1]

Wrong:

[1,1]

一种比较巧妙的方法在于hashmap在同一次遍历中动态生成,避免重用同一个元素。

Solution

One Pass HashMap - O(n) time, O(n) space (3ms, 99.76%)


class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if(map.containsKey(target - num)) {
                return new int[] {map.get(target - num), i};
            }
            map.put(num, i);
        }
        return new int[]{1,1};
    }
}

Brute Force - Two Loops - O(n^2) time, O(1) space

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 };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

Two Pass Hash Table: O(n) time, O(n) space - (8ms 56.82%)

Beware that the complement must not be nums[i] itself!

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

results matching ""

    No results matching ""