-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16-6.py
More file actions
34 lines (27 loc) · 686 Bytes
/
16-6.py
File metadata and controls
34 lines (27 loc) · 686 Bytes
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
# Given two arrays of integers, find the two elements with the smallest difference
a = [121, 38, 8]
b = [7, 348, 12]
pair = None
smallestSum = float('inf')
for i in a:
for j in b:
if abs(i - j) < smallestSum:
pair = (i, j)
smallestSum = i - j
print(pair)
l1 = sorted(a)
l2 = sorted(b)
i = j = 0
minimum = float('inf')
minPair = None
while i < len(l1) and j < len(l2):
diff = l1[i] - l2[j]
minPair = minPair if abs(diff) > minimum else (l1[i], l2[j])
minimum = min(minimum, abs(diff))
if diff < 0: # left is smaller than the right
i += 1
elif diff > 0:
j += 1
else:
break
print(minimum, minPair)