-
Notifications
You must be signed in to change notification settings - Fork 0
/
twoSums.py
51 lines (42 loc) · 1.32 KB
/
twoSums.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# encoding: utf-8
'''
@author: Lingcheng Dai
@contact: [email protected]
@file: twoSums.py
@time: 2018/7/30 10:24
'''
nums = [3, 2, 4]
target = 6
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# for i in range(len(nums)):
# if nums.index(target-nums[i])
# for j in range(len(nums)):
# if (nums[i]+nums[j] == target) & (i != j):
# return [i, j]
for i in range(len(nums)):
if (target-nums[i]) in nums:
if (nums.index(target - nums[i])) != i:
return [i, nums.index(target - nums[i])]
# for i in range(0, len(nums) - 1):
# for j in range(i + 1, len(nums)):
# if nums[i] + nums[j] == target:
# return [i, j]
dict = {}
for i in range(len(nums)):
if (target-nums[i]) in dict:
return [dict[(target-nums[i])], i]
else:
dict[nums[i]]=i
hash_table={}
for i, value in enumerate (nums):
if target-value in hash_table:
return hash_table[target-value], i
hash_table[value]=i
s = Solution
print(s.twoSum(s, nums, target))