zoukankan      html  css  js  c++  java
  • LeetCode-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.

    Solution:

     1 public class Solution {
     2     public class ValuePair {
     3         int val;
     4         int x;
     5         int y;
     6         public ValuePair(int v, int i, int j){
     7             val = v;
     8             x = i;
     9             y = j;
    10         }
    11     }
    12     public int kthSmallest(int[][] matrix, int k) {
    13         if (matrix.length==0 || matrix[0].length==0) return -1;
    14         
    15         PriorityQueue<ValuePair> q = new PriorityQueue<ValuePair>((a,b) -> (a.val-b.val));
    16         
    17         for (int i=0;i<matrix.length;i++){
    18             ValuePair p = new ValuePair(matrix[i][0],i,0);
    19             q.add(p);
    20         }
    21         
    22         ValuePair peek = null;
    23         for (int i=0;i<k-1;i++){
    24             peek = q.poll();
    25             peek.y++;
    26             if (peek.y<matrix[0].length){
    27                 peek.val = matrix[peek.x][peek.y];
    28                 q.add(peek);
    29             }
    30         }
    31         peek = q.poll();
    32         return peek.val;
    33     }
    34 }
  • 相关阅读:
    第二章——链表
    第一章:基本概念
    第八章
    画图
    关于写代码时的心态问题
    checked用id选择器找不到怎么办
    this指向问题
    es6箭头函数
    微信小程序——获取步数
    小程序——数据缓存
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5751581.html
Copyright © 2011-2022 走看看