-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTwo-Sum-II-Input-Array-Is-Sorted.py
50 lines (50 loc) · 1.34 KB
/
Two-Sum-II-Input-Array-Is-Sorted.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
## Python Solution 1:
class Solution:
def twoSum(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:
class Solution:
def twoSum(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:
class Solution:
def twoSum(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