-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_9.py
More file actions
71 lines (60 loc) · 1.56 KB
/
question_9.py
File metadata and controls
71 lines (60 loc) · 1.56 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# @Time : 2018/5/1 下午9:58
# @Author : cancan
# @File : question_9.py
# @Function : 两数之和
"""
Question:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
Example:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
class Solution1:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i, v in enumerate(nums):
d = target - v
if d in nums:
index = nums.index(d)
if index != i:
return [i, index]
class Solution2:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
t = {}
for i, v in enumerate(nums):
d = target - v
if d in t:
return [t[d], i]
else:
t[v] = i
class Solution3:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
t = {}
for i in range(len(nums)):
d = target - nums[i]
if d in t:
return [t[d], i]
else:
t[nums[i]] = i
if __name__ == "__main__":
s = Solution3()
d = [3, 2, 4]
t = 6
print(s.twoSum(d, t))