LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

原题链接在这里:https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/description/

题目:

You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.

You are allowed to choose exactly one element from each row to form an array.

Return the kth smallest array sum among all possible arrays.

Example 1:

Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.

Example 2:

Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17

Example 3:

Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  

Constraints:

  • m == mat.length
  • n == mat.length[i]
  • 1 <= m, n <= 40
  • 1 <= mat[i][j] <= 5000
  • 1 <= k <= min(200, nm)
  • mat[i] is a non-decreasing array.

题解:

We know how to find the kth smallest sum for 2 arrays.

Now we have a matrix. We can start with 2, merge it into a new array and continue with rest rows of matrix.

Each time, we keep the k smallest sums into a new array and continue with the next row.

Time Complexity: O(m * (n + k) * logn)). m = mat.length. n = mat[0].length. 

Space: O(k + n).

AC Java:

 1 class Solution {
 2     public int kthSmallest(int[][] mat, int k) {
 3         int[] row = mat[0];
 4         for(int r = 1; r < mat.length; r++){
 5             row = kSmall(row, mat[r], k);
 6         }
 7 
 8         return row[k - 1];
 9     }
10 
11     private int[] kSmall(int[] nums1, int[] nums2, int k){
12         List<Integer> res = new ArrayList<>();
13         int m = nums1.length;
14         int n = nums2.length;
15         PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a[2], b[2]));
16         for(int j = 0; j < n; j++){
17             minHeap.add(new int[]{0, j, nums1[0] + nums2[j]});
18         }
19 
20         while(k-- > 0 && !minHeap.isEmpty()){
21             int[] cur = minHeap.poll();
22             res.add(cur[2]);
23             if(cur[0] == m - 1){
24                 continue;
25             }
26 
27             minHeap.add(new int[]{cur[0] + 1, cur[1], nums1[cur[0] + 1] + nums2[cur[1]]});
28         }
29 
30         int[] resArr = new int[res.size()];
31         for(int i = 0; i < resArr.length; i++){
32             resArr[i] = res.get(i);
33         }
34 
35         return resArr;
36     }
37 }

类似Find K Pairs with Smallest Sums.

posted @ 2024-04-07 10:22  Dylan_Java_NYC  阅读(6)  评论(0编辑  收藏  举报