401.Kth Smallest Number in Sorted Matrix-排序矩阵中的从小到大第k个数(中等题)
来源:互联网 发布:怎样翻墙上外网 知乎 编辑:程序博客网 时间:2024/06/06 05:00
排序矩阵中的从小到大第k个数
题目
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。样例
给出 k = 4 和一个排序矩阵:
挑战
使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。
题解
使用优先队列进行最小堆排序,每次选取最小的元素,第K次选择的就是第K大元素。
public class Solution { class Pair { public int x, y, val; public Pair(int x, int y, int val) { this.x = x; this.y = y; this.val = val; } } /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ public int kthSmallest(int[][] matrix, int k) { int[] dx = new int[]{0, 1}; int[] dy = new int[]{1, 0}; int n = matrix.length; int m = matrix[0].length; boolean[][] hash = new boolean[n][m]; PriorityQueue<Pair> minHeap = new PriorityQueue<Pair>(k, new Comparator<Pair>() { public int compare(Pair a, Pair b) { return a.val - b.val; } }); minHeap.add(new Pair(0, 0, matrix[0][0])); for(int i = 0; i < k - 1; i++) { Pair cur = minHeap.poll(); for(int j = 0; j < 2; j++) { int next_x = cur.x + dx[j]; int next_y = cur.y + dy[j]; if(next_x < n && next_y < m && !hash[next_x][next_y]) { hash[next_x][next_y] = true; Pair next_Pair = new Pair(next_x, next_y, matrix[next_x][next_y]); minHeap.add(next_Pair); } } } return minHeap.peek().val; }}
Last Update 2016.11.15
0 0
- 401.Kth Smallest Number in Sorted Matrix-排序矩阵中的从小到大第k个数(中等题)
- lintcode kth-smallest-number-in-sorted-matrix 排序矩阵中的从小到大第k个数
- 378. Kth Smallest Element in a Sorted Matrix(查找矩阵中第k小的数)
- 排序矩阵中的从小到大第k个数
- 排序矩阵中的从小到大第k个数
- LintCode_401 Kth Smallest Number in Sorted Matrix
- LintCode-排序矩阵中的从小到大第k个数
- 题目:排序矩阵中的从小到大第k个数
- lintcode(401)排序矩阵中的从小到大第k个数
- LintCode 401-排序矩阵中的从小到大第k个数
- 排序矩阵中的从小到大第k个数-LintCode
- Leetcode 378 - Kth Smallest Element in a Sorted Matrix(二分+杨氏矩阵)
- 编程之 最小的K个数 216 Kth Largest Element in an Array 378. Kth Smallest Element in a Sorted Matrix
- leetcode378:Kth Smallest Element in a Sorted Matrix(medium)
- Kth Smallest Element in a Sorted Matrix (Leetcode)二分法
- 378. Kth Smallest Element in a Sorted Matrix (二分)
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Unity插件之Unity调用C#编译的DLL
- RPG游戏经典的系统架构
- 【shader】动态天空球
- 斜45度Tiiled坐标计算
- Java编程基础-方法
- 401.Kth Smallest Number in Sorted Matrix-排序矩阵中的从小到大第k个数(中等题)
- 告诉你ListView的Adapter应该写在Activity外面还是里面
- leetCode No.147 Insertion Sort
- 同义词概述
- 巴西游戏如何做好本地化?
- 在win10平台下快速查找占用端口的服务
- linux中强大且常用命令:find、grep
- 汉诺塔——递归入门
- 深入理解HTTP协议