LeetCode 378. 有序矩阵中第 K 小的元素

题目描述

378. 有序矩阵中第 K 小的元素

image-20250528225537083

思路分析

最小堆

二分查找

image-20250528225945990

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
type Element struct {
	val int
	row int
	col int
}

type MinHeap []Element

func (h MinHeap) Len() int { return len(h) }

func (h MinHeap) Less(i, j int) bool { return h[i].val < h[j].val }

func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(Element))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func kthSmallest(matrix [][]int, k int) int {
	n := len(matrix)
	h := &MinHeap{}
	heap.Init(h)

	// 将每行的第一个元素和其位置放入最小堆
	for i := 0; i < n; i++ {
		heap.Push(h, Element{val: matrix[i][0], row: i, col: 0})
	}

	// 弹出堆顶元素,直到弹出第 k 小的元素
	for i := 0; i < k-1; i++ {
		elem := heap.Pop(h).(Element)
		if elem.col+1 < n {
			// 如果当前行还有更多元素,加入下一个元素到堆中
			heap.Push(h, Element{val: matrix[elem.row][elem.col+1], row: elem.row, col: elem.col + 1})
		}
	}

	return heap.Pop(h).(Element).val
}

image-20250528225915991

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func countLessEqual(matrix [][]int, mid int) int {
	count := 0
	n := len(matrix)
	row, col := n-1, 0
	for row >= 0 && col < n {
		if matrix[row][col] <= mid {
			count += row + 1
			col++
		} else {
			row--
		}
	}
	return count
}

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
		if countLessEqual(matrix, mid) < k {
			left = mid + 1
		} else {
			right = mid
		}
	}

	return left
}

➡️ 点击查看 Java 题解

1
write your code here

相似题目

本文作者:
本文链接: https://hgnulb.github.io/blog/2025/32635930
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!