leetcode-632-最小区间
题目描述:
方法一:排序滑窗
class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: lst = [] for i in range(len(nums)): for j in range(len(nums[i])): lst.append((nums[i][j],i)) lst.sort(key=lambda x:x[0]) i = 0,k = 0 ans = [-10**9, 10**9] count = {} for j in range(len(lst)): if lst[j][1] not in count.keys(): k+=1 count[lst[j][1]] = 1 else: count[lst[j][1]] += 1 if k==len(nums): while count[lst[i][1]]>1: count[lst[i][1]] -= 1 i += 1 if ans[1]-ans[0]>lst[j][0]-lst[i][0]: ans[1],ans[0] = lst[j][0],lst[i][0] return ans
方法二:堆
class Solution: def smallestRange(self, nums): from heapq import heappush, heappop k = len(nums) heap = [] tmpmax=-1000000 for i in range(k): heappush(heap, [nums[i][0], i, 0]) tmpmax=max(tmpmax, nums[i][0]) ans=[] while True: cur=heappop(heap) cand=[cur[0], tmpmax] if not len(ans) or (cand[1]-cand[0]<ans[1]-ans[0] or (cand[1]-cand[0]==ans[1]-ans[0] and cand[0]<ans[0])): ans=cand idx, pt=cur[1], cur[2] if pt+1>=len(nums[idx]): break new_insert=nums[idx][pt+1] tmpmax=max(tmpmax, new_insert) heappush(heap, [new_insert, idx, pt+1]) return ans