本文共 626 字,大约阅读时间需要 2 分钟。
题目:给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8,
返回 13。
package com.lcz.leetcode;/** * 有序矩阵中第K小的元素 * @author LvChaoZhang * */import java.util.*;public class Leetcode378 { class Solution{ // 优先级队列 private PriorityQueuequeue; private int limit; public int kthSmallest(int[][] matrix,int k) { limit = k; // 大顶堆 queue = new PriorityQueue<>((a,b)->Integer.compare(b, a)); for(int[] a:matrix) { for(int value:a) { if(limit>queue.size()) { queue.offer(value); }else if(value
转载地址:http://gwwdf.baihongyu.com/