Seawolf 发表于 2019-9-29 09:26:09

leetcode 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],
   ,
   
],
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.length; j++){
               
                queue.offer(matrix);
            }
      }
      
      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.length;
      int start = matrix, end = matrix;
      
      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.length;
      int c = col - 1;
      int count = 0;
      for(int i = 0; i < row ; i++){
            while(c >= 0 && matrix > n) c--;
            count += c + 1;
      }
      return count;
    }
}
页: [1]
查看完整版本: leetcode 378. Kth Smallest Element in a Sorted Matrix