-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTwoNumbersWithSum.py
More file actions
52 lines (52 loc) · 1.42 KB
/
Copy pathTwoNumbersWithSum.py
File metadata and controls
52 lines (52 loc) · 1.42 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
### Python Solution 1:
class Solution:
def FindNumbersWithSum(self, nums, target):
# write code here
res = []
n = len(nums)
if n==0:
return res
for i in range(n):
for j in range(i+1,n):
if nums[i]+nums[j]==target:
res.append(nums[i])
res.append(nums[j])
return res
return res
### Python Solution 2:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, nums, target):
# write code here
res = []
record = {}
n = len(nums)
if n==0:
return res
for index,num in enumerate (nums):
complement = target - num
if complement in record:
res.append(complement)
res.append(num)
return res
record[num] = index
return res
### Python Solution 3:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, nums, target):
# write code here
res = []
n = len(nums)
left = 0
right = n-1
while right>left:
if nums[left]+nums[right]==target:
res.append(nums[left])
res.append(nums[right])
return res
if nums[left]+nums[right]>target:
right-=1
else:
left+=1
return res