排序矩阵中的从小到大第k个数
来源:互联网 发布:学生电脑软件下载 编辑:程序博客网 时间:2024/06/04 23:02
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
样例
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
挑战
排序矩阵的定义为:每一行递增,每一列也递增。
样例
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
挑战
使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。
import java.util.Comparator;import java.util.PriorityQueue;import java.util.Scanner;/** * 在一个排序矩阵中找从小到大的第 k 个整数。排序矩阵的定义为:每一行递增,每一列也递增。样例给出 k = 4 和一个排序矩阵:[ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9],]返回 5。挑战 使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。 * * @author Dell * */class Node{public int x;public int y;public int val;public Node(int x, int y, int val){this.x=x;this.y=y;this.val=val;}}public class Test401 {//直接放入优先队列,此方法没有利用矩阵是排序的特点,时间复杂度O(m*n),所以超时 public static int kthSmallest1(int[][] matrix,int k) { int m=matrix.length; int n=matrix[0].length; if(k<0||k>m*n) return 0; int result=0; PriorityQueue<Integer> p=new PriorityQueue<>(); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { p.offer(matrix[i][j]); } } for(int i=0;i<k;i++) { if(i==k-1) result=p.poll(); p.poll(); } return result; } public static int kthSmallest2(int[][] matrix, int k) { int m =matrix.length; if(m==0) return 0; int n=matrix[0].length; boolean[][] hash=new boolean[m][n]; int[] dx=new int[]{0,1}; int[] dy=new int[]{1,0}; PriorityQueue<Node> q=new PriorityQueue<Node>(new Comparator<Node>(){@Overridepublic int compare(Node o1, Node o2) {return o1.val-o2.val;} }); q.offer(new Node(0,0,matrix[0][0])); hash[0][0]=true; for(int i=0;i<k-1;i++) { Node temp=q.poll(); for(int j=0;j<2;j++) { int new_x=temp.x+dx[j]; int new_y=temp.y+dy[j]; Node temp1=new Node(new_x,new_y,0); if(new_x<m&&new_y<n&&hash[new_x][new_y]==false) { hash[new_x][new_y]=true; temp1.val=matrix[new_x][new_y]; q.offer(temp1); } } } return q.peek().val; } public static void main(String[] args) {Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int n=sc.nextInt(); int[][] a=new int[m][n]; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { a[i][j]=sc.nextInt(); } } int k=sc.nextInt(); System.out.println(kthSmallest2(a,k));}}
阅读全文
0 0
- 排序矩阵中的从小到大第k个数
- 排序矩阵中的从小到大第k个数
- LintCode-排序矩阵中的从小到大第k个数
- 题目:排序矩阵中的从小到大第k个数
- lintcode(401)排序矩阵中的从小到大第k个数
- LintCode 401-排序矩阵中的从小到大第k个数
- 排序矩阵中的从小到大第k个数-LintCode
- 排序矩阵(杨氏矩阵)中的从小到大第k个数(C++)
- lintcode排序矩阵中的从小到大第k个数-401(Java版)
- lintcode kth-smallest-number-in-sorted-matrix 排序矩阵中的从小到大第k个数
- 401.Kth Smallest Number in Sorted Matrix-排序矩阵中的从小到大第k个数(中等题)
- 排序矩阵(杨氏矩阵)找从小到大的第K个数(C++)
- 非排序寻找从小到大第3400个数
- 非排序寻找从小到大第3400个数
- Leetcode004--排序数组寻找第k个数
- 寻找数组中的第k个数
- 寻找数组中的第k个数(序)
- N个数中的第k个最大值
- 77 Combinations(组合数)
- 自动装配、JavaConfig、XML 三种方案之间,怎么导入和混合配置?
- Struts2知识点回顾(二)Struts2项目准备和配置文件结构
- 笔试题2
- 敲程序时遇到的一些逗比问题
- 排序矩阵中的从小到大第k个数
- c3p0连接池NullPointerException
- 输出负数个数以及所有非负数的平均值
- 不重启机器(Centos)修改主机名
- mapnik的TextSymbolizer类的功能缺陷
- BZOJ 1188 分裂游戏 (博弈论)
- K-means聚类算法
- 修改CentOS 7的系统默认语言
- TreeSet中引用类型的排序