1.Two Sum I

1.Description(Easy)

Given an array of integers, find two numbers such that they add up to a specific target number.

The functiontwoSumshould 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) areNOTzero-based.

Notice

You may assume that each input would have exactly one solution

Example

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

return[1, 2]

Challenge

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time

  • O(n) Space, O(n) Time

2.Code

Version 1: Sort+Two pointers(空间上更好)--O(nlogn)--Time limit exceed

先排序,head在头,tail在尾。

sum>target --> tail--

sum<target --> head++

Version 2: HashMap(时间上更好) O(n)

可以通过一个哈希表减少时间复杂度:

这样,由于哈希表的查询时间为 O(1),算法的时间复杂度降低到 O(N),但是需要 O(N) 的空间复杂度来存储哈希表。不过综合来看,是要比暴力解法高效的。

我觉得 Two Sum 系列问题就是想教我们如何使用哈希表处理问题

Extend:

(Retuers phone interview):

no sorted arrays, have duplicates,return the number of pairs

先用一个hashmap记录值和他们出现的次数。

载一次遍历数组,如果target-array[i]存在,就把他们的数量相乘就是他们pair的数量。

比如{1,1,1,1,3,3,4,5} target=4,对于1,3这个pair来说有4*2=8对。

但是这里有个特殊情况,target-array[i] == array[i]

比如{4,4,4,4,4,5,6,7} target=8;

对于4,4 这个pair来说,按照上面的做法是5*5 = 25. 所以这种情况应该是 5*(5-1)/2 = 10

对于这个题目,如果array非常大。但是是reachable的,最好的应该是O(nlogn) sort,再用two pointer去做。

Two pointers:

这样就可以保证一个答案只被添加一次,重复的结果都会被跳过,可以得到正确的答案。不过,受这个思路的启发,其实前两个 if 分支也是可以做一点效率优化,跳过相同的元素:

Last updated

Was this helpful?