数组中的第k个最大元素

// 使用大顶堆
func findKthLargest(nums []int, k int) int {

for _, num := range nums {
    if len(h

}

}

func push(heap []int, v int) {
heap = append(heap, v)
up(heap, v, len(heap) - 1)
}

func up(heap []int, v int, lens int) {
now := lens
var p int
for {
p = (now - 1) / 2

    if nums[p] >= nums[now] {
        return 
    } 
     Swap(nums, now, j)
     now = p
}

}

func swap(nums []int, i, j int) {
tmp := nums[i]
nums[i] = nums[j]
nums[j] = tmp
}

func pop(nums []int) int {
swap(nums, 0, len(nums) - 1)
toReturn = heap[len(heap) - 1]
heap = heap[0:len(heap) - 1]
down(nums []int, len(heap))
return toReturn
}

func down(nums []int, lens int) {
var maxChild int
var childindex int
for now < lens {
l := 2 * now + 1
if l >= lens || l < 0 {
return
}
maxChild = nums[l]
childindex = l

    r := l + 1
    if r < lens && nums[r] > nums[l] {
        maxChild = nums[r]
        childindex = r
    }

    if maxChild > nums[now] {
        swap(nums, now, childindex)
        now = childindex
    } else {
        return
    }
}

}

你可能感兴趣的:(数组中的第k个最大元素)