当前位置:   article > 正文

Golang | Leetcode Golang题解之第215题数组中的第K个最大元素_golang leetcode 数组中的第k个最大元素

golang leetcode 数组中的第k个最大元素

题目:

题解:

  1. func findKthLargest(nums []int, k int) int {
  2. heapSize := len(nums)
  3. buildMaxHeap(nums, heapSize)
  4. for i := len(nums) - 1; i >= len(nums) - k + 1; i-- {
  5. nums[0], nums[i] = nums[i], nums[0]
  6. heapSize--
  7. maxHeapify(nums, 0, heapSize)
  8. }
  9. return nums[0]
  10. }
  11. func buildMaxHeap(a []int, heapSize int) {
  12. for i := heapSize/2; i >= 0; i-- {
  13. maxHeapify(a, i, heapSize)
  14. }
  15. }
  16. func maxHeapify(a []int, i, heapSize int) {
  17. l, r, largest := i * 2 + 1, i * 2 + 2, i
  18. if l < heapSize && a[l] > a[largest] {
  19. largest = l
  20. }
  21. if r < heapSize && a[r] > a[largest] {
  22. largest = r
  23. }
  24. if largest != i {
  25. a[i], a[largest] = a[largest], a[i]
  26. maxHeapify(a, largest, heapSize)
  27. }
  28. }
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/926502
推荐阅读
相关标签
  

闽ICP备14008679号