zoukankan      html  css  js  c++  java
  • 378. Kth Smallest Element in a Sorted Matrix

    Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

    Note that it is the kth smallest element in the sorted order, not the kth distinct element.

    Example:

    matrix = [
       [ 1,  5,  9],
       [10, 11, 13],
       [12, 13, 15]
    ],
    k = 8,
    
    return 13.
    

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ n2.

    题目含义:给定一个升序的矩阵,找到第k小的元素

    方法一:使用优先级队列

     1     public int kthSmallest(int[][] matrix, int k) {
     2         PriorityQueue<Integer> pq = new PriorityQueue<>();
     3         if (matrix.length == 0) return Integer.MAX_VALUE;
     4         for (int i = 0; i < matrix.length; i++) {
     5             for (int j = 0; j < matrix[0].length; j++) {
     6                 pq.add(matrix[i][j]);
     7             }
     8         }
     9         int i = 0;
    10         while (i < k - 1) {
    11             if (!pq.isEmpty()) pq.poll();
    12             i++;
    13         }
    14         if (!pq.isEmpty()) return pq.poll();
    15         return Integer.MAX_VALUE;        
    16     }
  • 相关阅读:
    层模型--绝对定位(position:absolute)
    什么是层模型?
    浮动模型
    流动模型(二)
    插值方法
    CFS调度分析(内核版本:2.6.34)
    CRC检验
    ubuntu误删home目录
    随想
    Android——Activity生命周期
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7723700.html
Copyright © 2011-2022 走看看