kth-smallest-number-in-sorted-matrix

Find the kth smallest number in at row and column sorted matrix.

[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]

注意点:

  • Comparator<Pair>的实现
  • PriorityQueue poll add
 1 import java.util.*;
 2 
 3 class Pair{
 4     public int x, y, val;
 5     public Pair(int x, int y, int val){
 6         this.x = x;
 7         this.y = y;
 8         this.val = val;
 9     }
10 }
11 
12 class PairComparator implements Comparator<Pair> {
13     public int compare(Pair a, Pair b){
14         return a.val - b.val;
15     }
16 }
17 
18 public class Solution {
19     /**
20      * @param matrix: a matrix of integers
21      * @param k: an integer
22      * @return: the kth smallest number in the matrix
23      */
24     public int kthSmallest(int[][] matrix, int k) {
25         // write your code here
26         int[] dx = {0, 1};
27         int[] dy = {1, 0};
28         int m = matrix.length;
29         int n = matrix[0].length;
30         boolean[][] visited = new boolean[m][n];
31         PriorityQueue<Pair> pq = new PriorityQueue<>(k, new PairComparator());
32         pq.add(new Pair(0, 0, matrix[0][0]));
33 
34         for (int i = 0; i < k - 1; i++){
35             Pair cur = pq.poll();
36             for (int j = 0; j < 2; j++){
37                 int x = cur.x + dx[j];
38                 int y = cur.y + dy[j];
39                 if (x < m && y < n && !visited[x][y]){
40                     pq.add(new Pair(x, y, matrix[x][y]));
41                     visited[x][y] = true;
42 
43                 }
44             }
45         }
46         return pq.peek().val;
47     }
48 }
View Code

相关文章:

  • 2022-12-23
  • 2021-10-14
  • 2021-10-07
  • 2022-12-23
  • 2022-01-17
  • 2021-12-17
  • 2021-11-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2022-02-22
相关资源
相似解决方案