Skip to content

Commit 640eec4

Browse files
committed
quick sort: top k
Change-Id: I8852538d7fb5df43f39e2493e85bedc68c8da4a2
1 parent f6bc324 commit 640eec4

File tree

1 file changed

+67
-26
lines changed

1 file changed

+67
-26
lines changed

Diff for: go/leetcode/215.数组中的第k个最大元素.go

+67-26
Original file line numberDiff line numberDiff line change
@@ -37,45 +37,86 @@
3737

3838
// @lc code=start
3939
import (
40-
"container/heap"
40+
// "container/heap"
41+
"math/rand"
4142
)
4243

43-
type myHeap []int
44+
// type myHeap []int
4445

45-
func (h *myHeap) Less(i, j int) bool {
46-
return (*h)[i] < (*h)[j]
47-
}
46+
// func (h *myHeap) Less(i, j int) bool {
47+
// return (*h)[i] < (*h)[j]
48+
// }
4849

49-
func (h *myHeap) Swap(i, j int) {
50-
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
51-
}
50+
// func (h *myHeap) Swap(i, j int) {
51+
// (*h)[i], (*h)[j] = (*h)[j], (*h)[i]
52+
// }
53+
54+
// func (h *myHeap) Len() int {
55+
// return len(*h)
56+
// }
5257

53-
func (h *myHeap) Len() int {
54-
return len(*h)
58+
// func (h *myHeap) Pop() (v interface{}) {
59+
// *h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1]
60+
// return
61+
// }
62+
63+
// func (h *myHeap) Push(v interface{}) {
64+
// *h = append(*h, v.(int))
65+
// }
66+
67+
func findKthLargest(nums []int, k int) int {
68+
// h := make(myHeap, 0)
69+
// heap.Init(&h)
70+
// for _, cur := range nums {
71+
// if h.Len() >= k {
72+
// if cur <= h[0] {
73+
// continue
74+
// }
75+
// heap.Pop(&h)
76+
// }
77+
// heap.Push(&h, cur)
78+
// }
79+
// return h[0]
80+
s := &solution{nums: nums}
81+
return s.call(len(nums)-k, 0, len(nums)-1)
5582
}
5683

57-
func (h *myHeap) Pop() (v interface{}) {
58-
*h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1]
59-
return
84+
type solution struct {
85+
nums []int
6086
}
6187

62-
func (h *myHeap) Push(v interface{}) {
63-
*h = append(*h, v.(int))
88+
// 用快排的分组思想,如果分组的界限是k,就可以返回了,否则继续2分。
89+
func (s *solution) call(k, left, right int) int {
90+
idx := s.partition(left, right)
91+
if k == idx {
92+
return s.nums[k]
93+
}
94+
if k > idx {
95+
return s.call(k, idx+1, right)
96+
}
97+
return s.call(k, left, idx-1)
6498
}
6599

66-
func findKthLargest(nums []int, k int) int {
67-
h := make(myHeap, 0)
68-
heap.Init(&h)
69-
for _, cur := range nums {
70-
if h.Len() >= k {
71-
if cur <= h[0] {
72-
continue
73-
}
74-
heap.Pop(&h)
100+
// 左闭右闭
101+
func (s *solution) partition(i, j int) int {
102+
if i >= j {
103+
return i
104+
}
105+
idx := rand.Intn(j-i) + i
106+
s.nums[idx], s.nums[i] = s.nums[i], s.nums[idx]
107+
d := s.nums[i]
108+
for i < j {
109+
for i < j && s.nums[j] >= d {
110+
j--
111+
}
112+
s.nums[i] = s.nums[j]
113+
for i < j && s.nums[i] < d {
114+
i++
75115
}
76-
heap.Push(&h, cur)
116+
s.nums[j] = s.nums[i]
77117
}
78-
return h[0]
118+
s.nums[i] = d
119+
return i
79120
}
80121

81122
// @lc code=end

0 commit comments

Comments
 (0)