Two Sum

We can use hash table to solve this problems

But pay attention that if the target is exactly double of the element, which will return the same indices.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class (object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
dict = {}
for i,item in enumerate(nums):
dict[item] = i
for i,item in enumerate(nums):
num = target - item
if(dict.has_key(num)):
if(dict[num] != i):
return [i,dict[num]]
return result