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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| package main
import ( "container/heap" "fmt" "math/rand" )
func findKthLargest(nums []int, k int) int { h := &minHeap{} heap.Init(h) for _, num := range nums { if h.Len() < k { heap.Push(h, num) } else if num > (*h)[0] { heap.Pop(h) heap.Push(h, num) } } return (*h)[0] }
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[:n-1] return x }
func findKthLargest_1(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 := rand.Intn(right-left+1) + left pivot := nums[pivotIndex] i, j := left, right for i <= j { for nums[i] < pivot { i++ } for nums[j] > pivot { j-- } if i <= j { nums[i], nums[j] = nums[j], nums[i] i++ j-- } }
if k <= j { return quickSelect(nums, left, j, k) } else if k >= i { return quickSelect(nums, i, right, k) } else { return nums[k] } }
func main() { testCases := []struct { nums []int k int expected int }{ {[]int{3, 2, 1, 5, 6, 4}, 2, 5}, {[]int{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4, 4}, }
for i, tc := range testCases { result := findKthLargest(tc.nums, tc.k) fmt.Printf("Test Case %d, Input: nums = %v, k = %d\n", i+1, tc.nums, tc.k)
if result == tc.expected { fmt.Printf("Test Case %d, Output: %d, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %d, FAIL (Expected: %d)\n", i+1, result, tc.expected) } } }
|