LeetCode 215. 数组中的第K个最大元素
题目描述
思路分析
经典的Top N 问题,可以使用快速选择算法来解决这个问题。
第 k 个最大的元素是第 len(nums) - k 个最小的元素
参考代码
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
func findKthLargest(nums []int, k int) int {
return quickSelect(nums, 0, len(nums)-1, len(nums)-k)
}
func quickSelect(nums []int, left, right, k int) int {
if left == right {
return nums[left]
}
pivotIndex := partition(nums, left, right)
if k == pivotIndex {
return nums[k]
} else if k < pivotIndex {
return quickSelect(nums, left, pivotIndex-1, k)
} else {
return quickSelect(nums, pivotIndex+1, right, k)
}
}
func partition(nums []int, left, right int) int {
pivotIndex := rand.Intn(right-left+1) + left
nums[left], nums[pivotIndex] = nums[pivotIndex], nums[left]
pivot := nums[left]
i, j := left, right
for i < j {
for i < j && nums[j] >= pivot {
j--
}
if i < j {
nums[i] = nums[j]
i++
}
for i < j && nums[i] <= pivot {
i++
}
if i < j {
nums[j] = nums[i]
j--
}
}
nums[i] = pivot
return i
}
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
// 定义最小堆
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
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.(int)) }
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func findKthLargest(nums []int, k int) int {
h := &MinHeap{}
heap.Init(h)
// 将前 k 个元素放入堆
for i := 0; i < k; i++ {
heap.Push(h, nums[i])
}
// 遍历剩下的元素,保持堆大小为 k
for i := k; i < len(nums); i++ {
if nums[i] > (*h)[0] {
heap.Pop(h)
heap.Push(h, nums[i])
}
}
// 堆顶元素就是第 k 个最大元素
return (*h)[0]
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用