赞
踩
题目:
题解:
- func findKthLargest(nums []int, k int) int {
- heapSize := len(nums)
- buildMaxHeap(nums, heapSize)
- for i := len(nums) - 1; i >= len(nums) - k + 1; i-- {
- nums[0], nums[i] = nums[i], nums[0]
- heapSize--
- maxHeapify(nums, 0, heapSize)
- }
- return nums[0]
- }
-
- func buildMaxHeap(a []int, heapSize int) {
- for i := heapSize/2; i >= 0; i-- {
- maxHeapify(a, i, heapSize)
- }
- }
-
- func maxHeapify(a []int, i, heapSize int) {
- l, r, largest := i * 2 + 1, i * 2 + 2, i
- if l < heapSize && a[l] > a[largest] {
- largest = l
- }
- if r < heapSize && a[r] > a[largest] {
- largest = r
- }
- if largest != i {
- a[i], a[largest] = a[largest], a[i]
- maxHeapify(a, largest, heapSize)
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。