Leetcode - Kth Smallest Element in a Sorted Matrix
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 }