博客
关于我
LeetCode 378.有序矩阵中第K小的元素
阅读量:246 次
发布时间:2019-03-01

本文共 1402 字,大约阅读时间需要 4 分钟。

给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。

请注意,它是 排序后 的第 k 小元素,而不是第 k 个 不同 的元素。

用最小堆维护候选集合

每次堆中取出一个元素 将它的右元素和下元素加入候选集合
用数组判断某个元素是否已经被加入过堆

class Solution {       class Node{           int x;        int y;        int val;        public Node(int x, int y, int val){               this.x = x;            this.y = y;            this.val = val;        }    }    class NodeComparator implements Comparator
{ public int compare(Node a, Node b){ return a.val - b.val; } } public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int[] cx = { 0, 1}; int[] cy = { 1, 0}; boolean[][] hash = new boolean[n][n]; Queue
minheap = new PriorityQueue<>(k, new NodeComparator()); minheap.add(new Node(0, 0, matrix[0][0])); int count = 0; while(!minheap.isEmpty()){ Node node = minheap.poll(); if(++count == k) return matrix[node.x][node.y]; for(int i = 0; i < 2; i++){ if(node.x + cx[i] < n && node.y + cy[i] < n && !hash[node.x + cx[i]][node.y + cy[i]]){ minheap.offer(new Node(node.x + cx[i], node.y + cy[i], matrix[node.x + cx[i]][node.y + cy[i]])); hash[node.x + cx[i]][node.y + cy[i]] = true; } } } return 0; }}

转载地址:http://rtvv.baihongyu.com/

你可能感兴趣的文章
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB可视化客户端管理工具之NoSQLbooster4mongo
查看>>
Mongodb学习总结(1)——常用NoSql数据库比较
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
mongodb定时备份数据库
查看>>
mppt算法详解-ChatGPT4o作答
查看>>
mpvue的使用(一)必要的开发环境
查看>>
MQ 重复消费如何解决?
查看>>
mqtt broker服务端
查看>>
MQTT 保留消息
查看>>
MQTT 持久会话与 Clean Session 详解
查看>>
MQTT工作笔记0007---剩余长度
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
Mqtt搭建代理服务器进行通信-浅析
查看>>
MS Edge浏览器“STATUS_INVALID_IMAGE_HASH“兼容性问题
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>
MSBuild 教程(2)
查看>>
msbuild发布web应用程序
查看>>
MSB与LSB
查看>>