- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTwoSum.py
More file actions
Latest commit
71 lines (69 loc) · 1.93 KB
/
Copy pathTwoSum.py
File metadata and controls
71 lines (69 loc) · 1.93 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
"""Given an array S of n integers,
find three integers in S such that the sum is equal to a given number,
target. Return the sum of the two integers.
You may assume that each input would have exactly one solution.
for example, [1,2,3,4,5] target = 6, return 1,5,
"""
# given a list of numbers and a target, return the two numbers whose sum is equal to target
# it is n^2
defTwoSum(listNum,target):
# sort thte list
newList=sorted(listNum)
solutions=set()
foriinnewList:
rest=target-i
forjinnewList:
ifj==rest:
solutions.add(tuple(sorted((i,j))))
returnsolutions
defTwoSumBiSearch(listNum,target):
newList=sorted(listNum)
solutions=set()
foriinnewList:
rest=target-i
ifbinarySearchIter(newList,rest,0,len(listNum)) ==True:
solutions.add(tuple(sorted( (i,rest) )))
returnsolutions
# make nlogn
# look up a number in binary search
# recursively
defbinarySearch(sortedList, num=None, start=None, end=None):
ifnumisNone:
raiseError("I can't search for nothing!")
ifstartisNone:
start=0
ifendisNone:
end=len(sortedList) -1
ifstart>end:
returnFalse
middleIdx= (start+end) /2
middle=sortedList[middleIdx]
ifnum<middle:
returnbinarySearch(sortedList,num,start,middleIdx-1)
elifnum>middle:
returnbinarySearch(sortedList,num,middleIdx+1, end)
else:
returnTrue
# iteratively
defbinarySearchIter(sortedList,num=None, start=None, end=None):
ifstartisNone:
start=0
ifendisNone:
end=len(sortedList) -1
whilestart<=end:
printstart, end
middleIdx= (start+end) /2
middle=sortedList[middleIdx]
ifnum>middle:
start=middleIdx+1
elifnum<middle:
end=middleIdx-1
else:
returnTrue
returnFalse
deftest():
arr= [1,2,3,4,5,7,9]
printTwoSum(arr,5)
printbinarySearchIter(arr,3)
# print TwoSumBiSearch(arr,5)
test()