카테고리 없음

[Leetcode/파이썬] 373. Find K Pairs with Smallest Sums

난쟁이 개발자 2025. 5. 25. 20:55
반응형

Find K Pairs with Smallest Sums

Difficulty: Medium


You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

 

Example 1:

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:

Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [[1,1],[1,1]]
Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

 

Constraints:

  • 1 <= nums1.length, nums2.length <= 105
  • -109 <= nums1[i], nums2[i] <= 109
  • nums1 and nums2 both are sorted in non-decreasing order.
  • 1 <= k <= 104
  • k <= nums1.length * nums2.length

 

class Solution:
    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
        res = []
        heap = []
        visited = set()

        heapq.heappush(heap, [nums1[0] + nums2[0], 0, 0])
        visited.add((0, 0))

        while k and heap :
            _, i, j = heapq.heappop(heap)
            res.append([nums1[i], nums2[j]])
            k -= 1

            if i + 1 < len(nums1) and (i + 1, j) not in visited :
                heapq.heappush(heap, [nums1[i+1] + nums2[j], i + 1, j])
                visited.add((i + 1, j))

            if j + 1 < len(nums2) and (i, j + 1) not in visited :
                heapq.heappush(heap, [nums1[i] + nums2[j + 1], i, j+1])
                visited.add((i, j + 1))

        return res

heap 을 이용한 문제 풀이이다. 문제의 조건을 보면, 각 배열들은 오름차순으로 정렬되어 있으며, 최종 정답에는 k 번째 까지의 배열 조합을 반환해야 한다. 여기서 배열 조합 역시 오름차순으로 정렬된 순서이다. 

정답 배열과 heap 배열을 만든다. 그리고 중복 방지를 위해 visited 집합을 만든다.

각 배열에 첫 번째 숫자들의 합, 첫 번째 배열의 인덱스, 두 번째 배열의 인덱스를 힙에 넣고, 방문 처리를 한다.

힙의 특성상 나중에 추가된 데이터라 하더라도 두 수의 합이 더 적은 쪽을 계속해서 res에 추가된다. 

반응형