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