|
| 1 | +# Time: O(nlogk) |
| 2 | +# Space: O(k) |
| 3 | + |
| 4 | +# You have k lists of sorted integers in ascending order. |
| 5 | +# Find the smallest range that includes at least one number from each of the k lists. |
| 6 | +# |
| 7 | +# We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c. |
| 8 | +# |
| 9 | +# Example 1: |
| 10 | +# Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] |
| 11 | +# Output: [20,24] |
| 12 | +# Explanation: |
| 13 | +# List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. |
| 14 | +# List 2: [0, 9, 12, 20], 20 is in range [20,24]. |
| 15 | +# List 3: [5, 18, 22, 30], 22 is in range [20,24]. |
| 16 | +# Note: |
| 17 | +# The given list may contain duplicates, so ascending order means >= here. |
| 18 | +# 1 <= k <= 3500 |
| 19 | +# -105 <= value of elements <= 10^5. |
| 20 | +# For Java users, please note that the input type has been changed to List<List<Integer>>. |
| 21 | +# And after you reset the code template, you'll see this point. |
| 22 | + |
| 23 | +class Solution(object): |
| 24 | + def smallestRange(self, nums): |
| 25 | + """ |
| 26 | + :type nums: List[List[int]] |
| 27 | + :rtype: List[int] |
| 28 | + """ |
| 29 | + left, right = float("inf"), float("-inf") |
| 30 | + min_heap = [] |
| 31 | + for row in nums: |
| 32 | + left = min(left, row[0]) |
| 33 | + right = max(right, row[0]) |
| 34 | + it = iter(row) |
| 35 | + heapq.heappush(min_heap, (next(it, None), it)) |
| 36 | + |
| 37 | + result = (left, right) |
| 38 | + while min_heap: |
| 39 | + (val, it) = heapq.heappop(min_heap) |
| 40 | + val = next(it, None) |
| 41 | + if val is None: |
| 42 | + break |
| 43 | + heapq.heappush(min_heap, (val, it)) |
| 44 | + left, right = min_heap[0][0], max(right, val); |
| 45 | + if right - left < result[1] - result[0]: |
| 46 | + result = (left, right) |
| 47 | + return result |
0 commit comments