forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmallest-range.py
32 lines (27 loc) · 860 Bytes
/
smallest-range.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
# Time: O(nlogk)
# Space: O(k)
import heapq
class Solution(object):
def smallestRange(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
left, right = float("inf"), float("-inf")
min_heap = []
for row in nums:
left = min(left, row[0])
right = max(right, row[0])
it = iter(row)
heapq.heappush(min_heap, (next(it, None), it))
result = (left, right)
while min_heap:
(val, it) = heapq.heappop(min_heap)
val = next(it, None)
if val is None:
break
heapq.heappush(min_heap, (val, it))
left, right = min_heap[0][0], max(right, val)
if right - left < result[1] - result[0]:
result = (left, right)
return result