Leetcode - Maximum Side Length of a Square with Sum Less than or Equal to Threshold
Leetcode - Kth Smallest Number in Multiplication Table

Leetcode - Kth Smallest Element in a Sorted Matrix

violet posted @ May 05, 2020 07:35:19 AM in 算法 with tags Algorithm Golang BinarySearch , 245 阅读

https://leetcode.com/problems/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.

 

func kthSmallest(matrix [][]int, k int) int {
    n := len(matrix)
    low := matrix[0][0]
    high := matrix[n-1][n-1]
    var mid, count int 
    for low <= high {
        mid = low + (high-low)/2
        count = find(matrix, mid)
        if count < k {
            low = mid + 1
        } else {
            high = mid - 1
        }
    }
    return low
}

func find(matrix [][]int, mid int) int {
    n := len(matrix)
    count := 0
    
    var j int
    for i := 0; i < n; i++ {
        for j = 0; j < n && matrix[i][j] <= mid; j++ {}
        count += j
    }
    return count
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter