鱼C论坛

 找回密码
 立即注册
查看: 1568|回复: 0

[学习笔记] leetcode 378. Kth Smallest Element in a Sorted Matrix

[复制链接]
发表于 2019-9-29 09:26:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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.

1.PriorityQueue
import java.util.Comparator; 
import java.util.PriorityQueue; 
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue <Integer> queue = new PriorityQueue <Integer>(matrix.length*matrix.length, new Comparator<Integer>(){
            public int compare(Integer n1, Integer n2){
                return n1 - n2;
            }
        });
        
        for(int i = 0 ; i < matrix.length; i++){
            
            for(int j = 0; j < matrix[0].length; j++){
                
                queue.offer(matrix[i][j]);
            }
        }
        
        int i = queue.peek();
        while(k != 0){
            
            i = queue.remove();
            
            k--;
        }
        
        return i;
    }
}

2.二分法
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        
        int row = matrix.length, col = matrix[0].length;
        int start = matrix[0][0], end = matrix[row-1][col-1];
        
        while(start <= end){
            int mid = (end - start)/2 + start;
            if(count(matrix, mid) >= k) end = mid - 1;
            else
                start = mid + 1;
        }
        return start;
    }
    
    public int count(int[][] matrix, int n){
        
        int row = matrix.length, col = matrix[0].length;
        int c = col - 1;
        int count = 0;
        for(int i = 0; i < row ; i++){
            while(c >= 0 && matrix[i][c] > n) c--;
            count += c + 1;
        }
        return count;
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-24 19:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表