Skip to content

Commit 56152b3

Browse files
author
Dima Koss
committed
add something, i did some time ago. Dont remember what it is
1 parent fb6b348 commit 56152b3

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

py3/medium/3closest/3closest.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def __init__(self):
3+
pass
4+
5+
def findClosest(self, target, nums):
6+
lf, rg = 0, len(nums) - 1
7+
while lf < rg:
8+
md = lf + (rg - lf) / 2
9+
if abs(nums[md] - target) < abs(nums[lf] - target):
10+
lf = md + 1
11+
else:
12+
rg = md - 1
13+
14+
if abs(nums[lf] - target) > abs(nums[rg] - target):
15+
return nums[rg]
16+
return nums[lf]
17+
18+
def threeSumClosest(self, nums, target):
19+
closest, closest_sum = list(), 100 * 1000
20+
nums = sorted(nums)
21+
for i1, num1 in enumerate(nums):
22+
for i2, num2 in enumerate(nums[i1+1:]):
23+
desired = target - num1 - num2
24+
closest_third = self.findClosest(desired, nums[i1 + i2 + 1:])
25+
if abs(closest_third + num1 + num2 - target) < closest_sum:
26+
closest_sum = abs(closest_third + num1 + num2 - target)
27+
closest_third = [num1, num2, closest]
28+
return closest_sum

py3/medium/3sum/3sum.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import collections
2+
3+
4+
class Solution:
5+
def __init__(self):
6+
self.triples = list()
7+
8+
def count(self, nums):
9+
ns = collections.defaultdict(list) # num to the list of it's indexes
10+
for place, n in enumerate(nums):
11+
ns[n].append(place)
12+
return ns
13+
14+
def threeSum(self, nums):
15+
ns = self.count(nums)
16+
used = set()
17+
for i1, num1 in enumerate(nums):
18+
for i2, num2 in enumerate(nums[i1 + 1:]):
19+
if (
20+
-(num1 + num2) in ns and
21+
# no duplicated
22+
(num1, num2, -(num1 + num2)) not in used and (
23+
len(ns[-(num1 + num2)]) > 2 or
24+
(
25+
# checking not the same numbers
26+
ns[-(num1 + num2)] != [i1, i2 + i1 + 1] and
27+
ns[-(num1 + num2)] != [i2 + i1 + 1, i1] and
28+
ns[-(num1 + num2)] != [i1] and
29+
ns[-(num1 + num2)] != [i2 + i1 + 1]
30+
)
31+
)
32+
):
33+
self.triples.append([num1, num2, -(num1 + num2)])
34+
tn = -(num1 + num2)
35+
used.add((num1, num2, tn))
36+
used.add((num2, num1, tn))
37+
used.add((num1, tn, num2))
38+
used.add((num2, tn, num1))
39+
used.add((tn, num1, num2))
40+
used.add((tn, num2, num1))
41+
return self.triples
42+
43+
44+
45+
def main(nums):
46+
return Solution().threeSum(ns)
47+
48+
def get_input(inp):
49+
return [int(x) for x in nums.split()]
50+
51+
def format_output(triples):
52+
pass

0 commit comments

Comments
 (0)