首页 > 代码库 > Two Sum | LeetCode OJ 解题报告

Two Sum | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/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.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

大体意思就是在一串数中找两个加起来等于目标数的下标(注意下标从1开始),假设只有一组解。


 

先上结论:

O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

暴力破解,时间复杂度O(n2),这个解会超时(Run Time Error)

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

建立哈希表查找,时间复杂度O(n)。


 

下面是我在https://oj.leetcode.com/discuss/上找的一个例子

def twoSum(self, num, target):    d = {}    for i in range(len(num)):        if num[i] in d:    # if d.has_key(num[i]):            return (d[num[i]]+1, i+1)        else:            d[target - num[i]] = i                            

假设A_value+B_value=http://www.mamicode.com/target 定义一个字典(B_value,A_index)键值对,遍历数组中的数。如果B_value在字典中,那么输出当前所遍历的数的下标(B_index)以及这个数的值在字典中所对应的A_index。如果不在,那么创建(target-A_value,A_index)

关于has_key() 和 in 的差别见

http://stackoverflow.com/questions/1323410/has-key-or-in

里面有人亲测 in 要稍微快一点点

如果把上述代码中 if num[i] in d:改为if num[i] in d.keys(): 会导致超时,貌似是因为查找list的时间是O(n),而查找dict的时间是O(1).

不太好意思贴自己写的代码,压根没想到用dict,在list里面折腾来折腾去的最后TLE

Two Sum | LeetCode OJ 解题报告