Leetcode 378. 有序矩阵中第 K 小的元素
1. 问题描述
2. 思路
- 左上角元素作为left,右下角元素作为right
- 执行二分查找
3. 代码
func kthSmallest(matrix [][]int, k int) int {
n := len(matrix)
left, right := matrix[0][0], matrix[n-1][n-1]
for left <= right {
mid := left + (right - left) / 2
smallNum := countSmall(matrix, mid, n)
if smallNum == k {
right = mid - 1
} else if smallNum < k {
left = mid + 1
} else {
right = mid - 1
}
}
return left
}
func countSmall(matrix [][]int, mid int, n int) int {
var num int
i, j := n - 1, 0
for i >= 0 && j <= n - 1 {
if matrix[i][j] <= mid {
j++
num += i + 1
} else {
i--
}
}
return num
}
|