排序矩阵中的从小到大第k个数

在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
样例
给出 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>(){

			@Override
			public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值