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%)

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

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

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

Last updated

Was this helpful?