Leetcode 378 Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:web软件开发方式 编辑:程序博客网 时间:2024/05/22 09:02
Leetcode 375 这个问题和375是同一个问题
可以用完全一样的方法来做
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.
public class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueue<Pairs> q = new PriorityQueue<>(); for(int j = 0; j < matrix[0].length; j++){ q.offer(new Pairs(matrix[0][j], 0, j)); } int count = 0; while(!q.isEmpty() && count++ < k - 1){ Pairs tmp = q.poll(); if(tmp.x == matrix.length - 1) continue; q.offer(new Pairs(matrix[tmp.x + 1][tmp.y], tmp.x + 1, tmp.y)); } return q.poll().val; } class Pairs implements Comparable<Pairs> {//这里就是用了一个class int x, y, val; public Pairs (int val, int x, int y) { this.x = x; this.y = y; this.val = val; } @Override public int compareTo (Pairs that) { return this.val - that.val; }}}
阅读全文
0 0
- LeetCode[378] Kth Smallest Element in a Sorted Matrix
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- leetCode No.378 Kth Smallest Element in a Sorted Matrix
- leetcode(378):Kth Smallest Element in a Sorted Matrix
- [Leetcode] 378 Kth Smallest Element in a Sorted Matrix
- Leetcode 378 Kth Smallest Element in a Sorted Matrix
- 【Leetcode】Kth Smallest Element in a Sorted Matrix
- LeetCode—378. Kth Smallest Element in a Sorted Matrix
- Leetcode 378. Kth Smallest Element in a Sorted Matrix
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix
- leetcode之 Kth Smallest Element in a Sorted Matrix
- LeetCode:Kth Smallest Element in a Sorted Matrix
- leetcode---Kth Smallest Element in a Sorted Matrix
- 【Leetcode】378. Kth Smallest Element in a Sorted Matrix
- Leetcode-378. Kth Smallest Element in a Sorted Matrix
- 378. [LeetCode]Kth Smallest Element in a Sorted Matrix
- mysql设计索引的原则与索引的选择
- 按list对象的某个方法返回值分组
- Python高级编程技巧
- springMVC 中几种获取request和response的方式
- RabbitMQ学习笔记(例子)
- Leetcode 378 Kth Smallest Element in a Sorted Matrix
- CAP原则(CAP定理)、BASE理论
- [bigdata-103] spring-cloud-01 服务注册 eureka server 单机版
- File获取功能
- OpenJudge 2989 糖果
- 自动轮播的Viewpager
- js创建对象的七种方式
- VirtualBox虚拟机与主机共享文件
- 数学问题——求回文平方数