题目链接:LeetCode-215. 数组中的第K个最大元素
func findKthLargest(nums []int, k int) int {
length := len(nums)
if k > length {
return -1
}
makeMinHeap(nums, k)
for i:=k;i<length;i++ {
if nums[i] > nums[0] {
nums[0], nums[i] = nums[i], nums[0]
minHeap(nums, 0, k)
}
}
return nums[0]
}
func makeMinHeap(arr []int, length int) {
// 从最后一个非叶子节点开始
for i:=(length/2-1); i>=0; i-- {
minHeap(arr, i, length)
}
}
// 最小堆化
func minHeap(arr []int, i int, length int) {
left, right := 2*i+1, 2*i+2
min := i
if left < length && arr[left] < arr[min] {
min = left
}
if right < length && arr[right] < arr[min] {
min = right
}
if min != i {
arr[i], arr[min] = arr[min], arr[i]
minHeap(arr, min, length)
}
}
func findKthLargest(nums []int, k int) int {
length := len(nums)
if k > length {
return -1
}
// 将nums构建为一个最大堆
makeMaxHeap(nums, length)
for i:=1; i<k; i++ {
nums[0], nums[length-i] = nums[length-i], nums[0]
maxHeap(nums, 0, length-i)
}
return nums[0]
}
// 最大堆
func makeMaxHeap(arr []int, length int) {
// 第一个非叶子节点
for i:=(length/2-1); i>=0; i-- {
maxHeap(arr, i, length)
}
}
// 最大堆化
func maxHeap(arr []int, i int, length int) {
l, r, max := 2*i+1, 2*i+2, i
if l<length && arr[l] > arr[max] {
max = l
}
if r<length && arr[r] > arr[max] {
max = r
}
if max != i {
arr[max], arr[i] = arr[i], arr[max]
maxHeap(arr, max, length)
}
}
func sortArray(nums []int) []int {
length := len(nums)
if length == 1 {
return nums
}
makeMaxHeap(nums, length)
for i:=length-1; i>0; i-- {
nums[0], nums[i] = nums[i], nums[0]
maxHeap(nums, 0, i)
}
return nums
}
// 构建最大堆
func makeMaxHeap(nums []int, length int) {
// 第一个非叶子结点
for i:=length/2-1; i>=0; i-- {
maxHeap(nums, i, length)
}
}
// 最大堆化
func maxHeap(nums []int, i int, length int) {
l, r, max := 2*i+1, 2*i+2, i
if l<length && nums[l] > nums[max] {
max = l
}
if r<length && nums[r] > nums[max] {
max = r
}
if max != i {
nums[max], nums[i] = nums[i], nums[max]
maxHeap(nums, max, length)
}
}
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeKLists(lists []*ListNode) *ListNode {
length := len(lists)
if length == 1 {
return lists[0]
}
// 去除空数组
for i:=0; i<length; i++ {
if lists[i] == nil {
lists[i], lists[length-1] = lists[length-1], lists[i]
length--
i--
}
}
newList := &ListNode{}
tmp := newList
// 最小化
makeMinHeap(lists, length)
for length > 0 && lists[0] != nil {
// 取出当前最小
tmp.Next = &ListNode{Val:lists[0].Val}
tmp = tmp.Next
lists[0] = lists[0].Next
if lists[0] == nil {
lists[0], lists[length-1] = lists[length-1], lists[0]
length--
}
if length > 0 && lists[0] != nil {
minHeap(lists, 0, length)
}
}
return newList.Next
}
func makeMinHeap(arr []*ListNode, length int) {
for i:=length/2-1; i>=0; i-- {
minHeap(arr, i, length)
}
}
func minHeap(arr []*ListNode, i, length int) {
left, right, min := 2*i+1, 2*i+2, i
if left<length && arr[left].Val < arr[min].Val {
min = left
}
if right<length && arr[right].Val < arr[min].Val {
min = right
}
if min != i {
arr[min], arr[i] = arr[i], arr[min]
minHeap(arr, min, length)
}
}