- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.py
More file actions
Latest commit
97 lines (82 loc) · 3.12 KB
/
Copy path16.py
File metadata and controls
97 lines (82 loc) · 3.12 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
fromtypingimportList
# Name: 3Sum Closest
# Link: https://leetcode.com/problems/3sum-closest/
# Method: Like 3sum, but keep track of best candidate
# Time: O(n^2)
# Space: O(n)
# Difficulty: Medium
classSolution:
defthreeSumClosest_inital(self, nums: List[int], target: int) ->int:
arr=sorted(nums)
n=len(arr)
current_dist=-1
current_closest=-1
foriinrange(n):
# 2sum with pointers
left=0
right=n-1
ct=target-arr[i]
whileleft<right:
# Skip the element we are currently on
ifleft==i:
left+=1
continue
ifright==i:
right-=1
continue
# Calc current elem, decide progess
# print(f"Setting c2s as {arr[left]} and {arr[right]}")
c2s=arr[left] +arr[right]
ifc2s>ct:
right-=1
elifc2s<ct:
left+=1
else:
returntarget
# print(f"Got intermediary for {i}, dist {abs(ct - c2s)} on target {ct} and c2s {c2s}")
ifcurrent_dist>0:
ifabs(ct-c2s) <current_dist:
current_dist=abs(c2s-ct)
current_closest=c2s+arr[i]
# print(f"Set sum to {current_closest} as dist is {current_dist}")
else: # Initial call
current_dist=abs(c2s-ct)
current_closest=c2s+arr[i]
# print(f"Set sum to {current_closest} as dist is {current_dist}")
returncurrent_closest
defthreeSumClosest(self, nums: List[int], target: int) ->int:
arr=sorted(nums)
n=len(arr)
current_dist=-1
current_closest=-1
foriinrange(n):
# 2sum with pointers
left=0
right=n-1
whileleft<i<right:
twosum_curr=arr[left] +arr[i] +arr[right]
iftwosum_curr>target:
right-=1
eliftwosum_curr<target:
left+=1
else:
returntarget
ifcurrent_dist>0:
ifabs(target-twosum_curr) <current_dist:
current_dist=abs(twosum_curr-target)
current_closest=twosum_curr
else: # Initial call
current_dist=abs(twosum_curr-target)
current_closest=twosum_curr
returncurrent_closest
if__name__=="__main__":
nums= [-1, 2, 1, -4]
t=1
sol=Solution()
assert2==sol.threeSumClosest(nums, t)
nums2= [1, 2, 3]
t2=0
assert6==sol.threeSumClosest(nums2, t2)
nums3= [1, 6, 9, 14, 16, 70]
t3=81
assert80==sol.threeSumClosest(nums3, t3)