题解 | #寻找第K大#

寻找第K大

https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

package main

func findKth(a []int, n int, K int) int {
	K = n - K + 1
	var heap []int
	heap = append(heap,0)
	for i := 0; i < K; i++ {
		heap = add(heap, a[i])
	}
	for i := K; i < n; i++ {
		if heap[1] > a[i] {
			heap[1] = a[i]
			down(heap, 1)
		}
	}
	return heap[1]
}

func down(heap []int, idx int) {
	le := len(heap)
	for idx < le {
		next := idx
		left := idx << 1
		if left < le && heap[left] > heap[next] {
			next = left
		}
		right := left + 1
		if right < le && heap[right] > heap[next] {
			next = right
		}
		if idx != next {
			tmp := heap[idx]
			heap[idx] = heap[next]
			heap[next] = tmp
			idx = next
		} else {
			break
		}
	}
}

func add(heap []int, val int) []int {
	heap = append(heap, val)
	idx := len(heap) - 1
	up(heap, idx)
	return heap
}

func up(heap []int, idx int) {
	for idx > 1 {
		parent := idx >> 1
		if heap[parent] >= heap[idx] {
			break
		}
		tmp := heap[parent]
		heap[parent] = heap[idx]
		heap[idx] = tmp
		idx = parent
	}
}

全部评论

相关推荐

11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
有趣的牛油果开挂了:最近这个阶段收到些杂七杂八的短信是真的烦
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务