378. 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 ? n^2.

一刷
题解:
方法1: 用一个heap, 然后装入第一行所有元素。
每次poll()一个出来,共poll() k次,得到的元素为(x, y, val), 然后在add进(x+1, y, val)

原理是:移除掉matrix中k-1个元素,在heap root的即为kth

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length;
        PriorityQueue pq = new PriorityQueue();
        for(int i=0; i1){
            Tuple cur = pq.poll();
            if(cur.x != m-1){
               pq.offer(new Tuple(cur.x+1, cur.y, matrix[cur.x+1][cur.y])); 
            }
            k--;
        }
        return pq.poll().val;
    }
    
    class Tuple implements Comparable{
        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 a){
            return this.val - a.val;
        }
    }
}

方法2: 无法理解

public int kthSmallest(int[][] matrix, int k) {
        int lo = matrix[0][0];
        int hi = matrix[matrix.length - 1][matrix[0].length - 1];
        while(lo < hi){
            int mid = lo + (hi - lo) / 2;
            int count = 0;
            int j = matrix[0].length - 1;
            for(int i = 0; i < matrix.length; i++){
                while(j >= 0 && matrix[i][j] > mid){
                    j--;
                }
                count += j + 1;
            }
            if(count < k){
                lo = mid + 1;
            }else{
                hi = mid;
            }
        }
        return lo;
    }

你可能感兴趣的:(378. Kth Smallest Element in a Sorted Matrix)