Loading

[Python手撕]查找和最小的 K 对数字

class Solution:
    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
        if not nums1 or not nums2:
            return []

        heap = []
        result = []

        for i in range(min(k, len(nums1))):
            heapq.heappush(heap, [nums1[i] + nums2[0], i, 0])

        while k > 0 and heap:
            sum, i, j = heapq.heappop(heap)
            result.append([nums1[i], nums2[j]])
            k -= 1

            if j + 1 < len(nums2):
                heapq.heappush(heap, [nums1[i] + nums2[j+1], i, j + 1])

        return(result)
posted @ 2024-09-11 09:20  Duancf  阅读(18)  评论(0)    收藏  举报