博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 378: Kth Smallest Element in Sorted Matrix
阅读量:7118 次
发布时间:2019-06-28

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

1. Use priority queue. Need to check whether one element has been double counted:

class Solution {    public int kthSmallest(int[][] matrix, int k) {        if (matrix.length == 0 || matrix[0].length == 0) return 0;        PriorityQueue
queue = new PriorityQueue<>((n1, n2) -> n1[0] - n2[0]); queue.offer(new int[]{matrix[0][0], 0, 0}); int i = 1; int[] current = new int[3]; Set
visited = new HashSet<>(); while (!queue.isEmpty() && i++ <= k) { current = queue.poll(); if (current[1] < matrix.length - 1 && !visited.contains((current[1] + 1)*matrix[0].length + current[2])) { queue.offer(new int[] {matrix[current[1] + 1][current[2]], current[1] + 1, current[2]}); visited.add((current[1] + 1)*matrix[0].length + current[2]); } if (current[2] < matrix[0].length - 1 && !visited.contains(current[1]*matrix[0].length + current[2] + 1)) { queue.offer(new int[] {matrix[current[1]][current[2] + 1], current[1], current[2] + 1}); visited.add(current[1] * matrix[0].length + current[2] + 1); } } return current[0]; }}

 

 

2 Binary search: For this kind of matrix, binary search should work as counting how many number satify the condition for each column and row.

class Solution {    public int kthSmallest(int[][] matrix, int k) {        if (matrix.length == 0 || matrix[0].length == 0) return 0;        int start = matrix[0][0], end = matrix[matrix.length - 1][matrix[0].length - 1];        while (start < end) {            int mid = start + (end - start) / 2;            int count = 0, j = matrix[0].length - 1;            for (int i = 0; i < matrix.length; i++) {                while (j >= 0 && matrix[i][j] > mid) j--;                count += j + 1;            }                        if (count < k) start = mid + 1;            else end = mid;        }        return start;    }}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7640671.html

你可能感兴趣的文章
最佳在线图表软件
查看>>
手挽手带你学React:三档 React-router4.x的使用
查看>>
React Hooks 梳理
查看>>
垃圾回收之引用计数
查看>>
Java的Interrupt与线程中断
查看>>
前端实用小工具
查看>>
大型云原生项目在数字化企业落地过程解密
查看>>
CentOS 7 编译安装 PHP 7
查看>>
vue跳转传参刷新后参数消失
查看>>
Java™ 教程(原子变量)
查看>>
非对称加密算法--RSA加密原理及运用
查看>>
精读《如何编译前端项目与组件》
查看>>
[ 逻辑锻炼] 用 JavaScript 做一个小游戏 ——2048 (详解版)
查看>>
【产品】产品经理常用的五大分析法
查看>>
Javascript二进制运算符的一些运用场景
查看>>
常见Promise面试题
查看>>
一个专科生学习JAVA目标月薪2万是否不切实际?
查看>>
保持ssh的连接不断开
查看>>
Java 高级算法——数组中查询重复的数字之二
查看>>
897-递增顺序查找树
查看>>