博客
关于我
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/

你可能感兴趣的文章
Netty工作笔记0010---Channel应用案例1
查看>>
Netty工作笔记0011---Channel应用案例2
查看>>
Netty工作笔记0012---Channel应用案例3
查看>>
Netty工作笔记0013---Channel应用案例4Copy图片
查看>>
Netty工作笔记0014---Buffer类型化和只读
查看>>
Netty工作笔记0015---MappedByteBuffer使用
查看>>
Netty工作笔记0016---Buffer的分散和聚合
查看>>
Netty工作笔记0017---Channel和Buffer梳理
查看>>
Netty工作笔记0018---Selector介绍和原理
查看>>
Netty工作笔记0019---Selector API介绍
查看>>
Netty工作笔记0020---Selectionkey在NIO体系
查看>>
Netty工作笔记0021---NIO编写,快速入门---编写服务器
查看>>
Netty工作笔记0022---NIO快速入门--编写客户端
查看>>
Vue踩坑笔记 - 关于vue静态资源引入的问题
查看>>
Netty工作笔记0024---SelectionKey API
查看>>
Netty工作笔记0025---SocketChannel API
查看>>
Netty工作笔记0026---NIO 网络编程应用--群聊系统1---编写服务器1
查看>>
Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
查看>>
Netty工作笔记0028---NIO 网络编程应用--群聊系统3--客户端编写1
查看>>
Netty工作笔记0029---NIO 网络编程应用--群聊系统4--客户端编写2
查看>>