TheAlgorithms-Python
71 строка · 2.1 Кб
1"""
2smallest_range function takes a list of sorted integer lists and finds the smallest
3range that includes at least one number from each list, using a min heap for efficiency.
4"""
5
6from heapq import heappop, heappush7from sys import maxsize8
9
10def smallest_range(nums: list[list[int]]) -> list[int]:11"""12Find the smallest range from each list in nums.
13
14Uses min heap for efficiency. The range includes at least one number from each list.
15
16Args:
17nums: List of k sorted integer lists.
18
19Returns:
20list: Smallest range as a two-element list.
21
22Examples:
23>>> smallest_range([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]])
24[20, 24]
25>>> smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
26[1, 1]
27>>> smallest_range(((1, 2, 3), (1, 2, 3), (1, 2, 3)))
28[1, 1]
29>>> smallest_range(((-3, -2, -1), (0, 0, 0), (1, 2, 3)))
30[-1, 1]
31>>> smallest_range([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
32[3, 7]
33>>> smallest_range([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
34[0, 0]
35>>> smallest_range([[], [], []])
36Traceback (most recent call last):
37...
38IndexError: list index out of range
39"""
40
41min_heap: list[tuple[int, int, int]] = []42current_max = -maxsize - 143
44for i, items in enumerate(nums):45heappush(min_heap, (items[0], i, 0))46current_max = max(current_max, items[0])47
48# Initialize smallest_range with large integer values49smallest_range = [-maxsize - 1, maxsize]50
51while min_heap:52current_min, list_index, element_index = heappop(min_heap)53
54if current_max - current_min < smallest_range[1] - smallest_range[0]:55smallest_range = [current_min, current_max]56
57if element_index == len(nums[list_index]) - 1:58break59
60next_element = nums[list_index][element_index + 1]61heappush(min_heap, (next_element, list_index, element_index + 1))62current_max = max(current_max, next_element)63
64return smallest_range65
66
67if __name__ == "__main__":68from doctest import testmod69
70testmod()71print(f"{smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])}") # Output: [1, 1]72