Kth Smallest Element in a Sorted Matrix

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.

本题只需记录每行最小数位置,存在temIndex中,每次找到n个最小位置中的最小位置,使其加1,继续循环直到循环次数大于k

public class KthSmall {
public static void main(String[] args) {
	System.out.println( kthSmallest(new int[][]{{1,5, 9},{10,11,13},{12,13,15}}, 8));
}
public static int kthSmallest(int[][] matrix, int k) {
	int[] tem=new int[matrix.length];
	int[] temIndex=new int[matrix.length];
	int tar=0;
	for(int i=0;i<k;i++){
		for(int j=0;j<matrix.length;j++)
			tem[j]=matrix[j][temIndex[j]];
		int temm=findSmall(tem, 0, tem.length-1);
		if(i==k-1){
			tar=matrix[temm][temIndex[temm]];
		}
		if(temIndex[temm]==matrix.length-1){
			matrix[temm][temIndex[temm]]=Integer.MAX_VALUE;
		}else {
			temIndex[temm]++;
		}
		
	}
    return tar;
}
static int findSmall(int[] t,int start,int stop){
	if(start==stop)
		return start;
	else {
		int zuo=findSmall(t, start, (start+stop)/2);
		int you=findSmall(t, (start+stop)/2+1, stop);
		if(t[zuo]<t[you])
			return zuo;
		else {
			return you;
		}
	}
}
}

之后又改进了一下:

public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
        for(int j = 0; j <= n-1; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
        for(int i = 0; i < k-1; i++) {
            Tuple t = pq.poll();
            if(t.x == n-1) continue;
            pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
        }
        return pq.poll().val;
    }
}

class Tuple implements Comparable<Tuple> {
    int x, y, val;
    public Tuple (int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }
    
    @Override
    public int compareTo (Tuple that) {
        return this.val - that.val;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值