Find K Pairs with Smallest Sums

ps
링크leetcode.com/…
출처LeetCode
문제 번호373
문제명Find K Pairs with Smallest Sums
레벨Medium
분류

fracturing search

시간복잡도O(klogk)
인풋사이즈k<=10^4
사용한 언어Python
제출기록923ms
해결날짜2024/10/16

코드

"""Solution code for "LeetCode 373. Find K Pairs with Smallest Sums".

- Problem link: https://leetcode.com/problems/find-k-pairs-with-smallest-sums
- Solution link: http://www.teferi.net/ps/problems/leetcode/373
"""

import heapq
from typing import List


class Solution:
    def kSmallestPairs(
        self, nums1: List[int], nums2: List[int], k: int
    ) -> List[List[int]]:
        heap = [(nums1[0] + nums2[0], 0, 0)]
        answer = []
        for _ in range(k):
            _, ind1, ind2 = heapq.heappop(heap)
            answer.append([nums1[ind1], nums2[ind2]])
            if ind2 == 0 and ind1 + 1 < len(nums1):
                heapq.heappush(
                    heap, (nums1[ind1 + 1] + nums2[ind2], ind1 + 1, ind2)
                )
            if ind2 + 1 < len(nums2):
                heapq.heappush(
                    heap, (nums1[ind1] + nums2[ind2 + 1], ind1, ind2 + 1)
                )
        return answer