Skip to content

Commit a95033f

Browse files
author
lishulong
committed
two sum 56 ms
1 parent 34c0940 commit a95033f

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

python3/1.Two Sum(两数之和).py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,29 @@
3939

4040

4141
class Solution:
42-
def twoSum(self, nums, target):
42+
def twoSum(self, nums: list, target):
4343
"""
4444
:type nums: List[int]
4545
:type target: int
4646
:rtype: List[int]
4747
"""
48-
48+
dic = {}
49+
for i, num in enumerate(nums):
50+
c = target - num
51+
if dic.get(c) is not None:
52+
return [nums.index(c), i]
53+
else:
54+
dic[num] = i
55+
56+
raise Exception('No two sum solution')
57+
58+
59+
if __name__ == '__main__':
60+
# 出现相同的元素
61+
lis = [3, 3, 3, 3, 44, 5, 3]
62+
tar = 6
63+
64+
# [3, 2, 4]
65+
# 6
66+
# 在使用索引实现位置的时候要注意了,in的使用会出现 [0,0]
67+
print(Solution().twoSum(lis, tar))

0 commit comments

Comments
 (0)