-
Notifications
You must be signed in to change notification settings - Fork 19
/
2.8. smallest-difference.py
43 lines (36 loc) · 1.15 KB
/
2.8. smallest-difference.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
# def smallestDifference(arrayOne, arrayTwo): # O(n2)
# # Write your code here.
# smallest = [float('inf'), float('-inf')]
# for one in arrayOne:
# for two in arrayTwo:
# if abs(smallest[0] - smallest[1]) > abs(one - two):
# smallest = [one, two]
# return smallest
def smallestDifference(arrayOne, arrayTwo):
# Write your code here.
arrayOne.sort()
arrayTwo.sort()
smallest = [float('inf'), float('-inf')]
first_idx = 0
second_idx = 0
while True:
first = arrayOne[first_idx]
second = arrayTwo[second_idx]
expected = abs(first - second)
if abs(smallest[0] - smallest[1]) > expected:
smallest = [first, second]
if first == second:
break
elif first < second:
if first_idx + 1 < len(arrayOne):
first_idx += 1
else:
break
else: # first > second
if second_idx + 1 < len(arrayTwo):
second_idx += 1
else:
break
return smallest
if __name__ == '__main__':
smallestDifference([1, 2, 3, 4], [3, 2, 1])