-
Notifications
You must be signed in to change notification settings - Fork 0
/
letcode_1_两数之和.py
57 lines (50 loc) · 1.4 KB
/
letcode_1_两数之和.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
52
53
54
55
56
57
#!/usr/bin/env python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@File:letcode_1_两数之和.py
@Data:2019/7/9
@param:
@return:
"""
class Solutions:
def twoSum(self, nums: list, target: int) -> list:
"""
两数之和
:param nums: 数组
:param target: 目标数
:return:
"""
index = []
this_num = sorted(nums)
for i in range(len(nums)):
target = target - this_num[i]
if target == this_num[i]:
index.append(nums.index(this_num[i]))
index.append(nums.index(this_num[i], i + 1))
break
if target in nums:
index.append(nums.index(this_num[i]))
index.append(nums.index(target))
break
target = target + this_num[i]
return sorted(index)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = []
for index in range(len(nums)):
try:
if (target - nums[index]) in nums:
res.append(nums.index(target - nums[index], index + 1))
res.append(index)
except:
continue
return res
if __name__ == '__main__':
sol = Solution()
print(sol.twoSum([-1,-2,-3,-4,-5],-8))