Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 693 Bytes

堆.md

File metadata and controls

46 lines (35 loc) · 693 Bytes

Go 语言:

package main

import (
	"container/heap"
	"fmt"
	"sort"
)

type heap2 struct {
	sort.IntSlice
}

func (h heap2) Less(i, j int) bool { // 最小堆:h.IntSlice[i] < h.IntSlice[j];最大堆:h.IntSlice[i] > h.IntSlice[j];
	return h.IntSlice[i] > h.IntSlice[j]
}

func (h *heap2) Push(v interface{}) {
	h.IntSlice = append(h.IntSlice, v.(int))
}

func (h *heap2) Pop() interface{} {
	temp := h.IntSlice
	v := temp[len(temp)-1]
	h.IntSlice = temp[:len(temp)-1]
	return v
}

func (h *heap2) push(v int) {
	heap.Push(h, v)
}

func (h *heap2) pop() int {
	return heap.Pop(h).(int)
}

func main() {
	q := &heap2{[]int{3, 4, 1, 2, 4, 3}}
	heap.Init(q)
	fmt.Println(q)
}