github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/priority_queue/int64.go (about) 1 package priority_queue 2 3 import ( 4 "container/heap" 5 ) 6 7 type maxInt64Heap []int64 8 9 func (s maxInt64Heap) Len() int { 10 return len(s) 11 } 12 13 func (s maxInt64Heap) Less(i, j int) bool { 14 return s[i] > s[j] 15 } 16 17 func (s maxInt64Heap) Swap(i, j int) { 18 s[i], s[j] = s[j], s[i] 19 } 20 21 func (s *maxInt64Heap) Push(x interface{}) { 22 *s = append(*s, x.(int64)) 23 } 24 25 func (s *maxInt64Heap) Pop() interface{} { 26 if len(*s) == 0 { 27 return nil 28 } 29 q := (*s)[len(*s)-1] 30 *s = (*s)[:len(*s)-1] 31 return q 32 } 33 34 type minInt64Heap []int64 35 36 func (s minInt64Heap) Len() int { 37 return len(s) 38 } 39 40 func (s minInt64Heap) Less(i, j int) bool { 41 return s[i] < s[j] 42 } 43 44 func (s minInt64Heap) Swap(i, j int) { 45 s[i], s[j] = s[j], s[i] 46 } 47 48 func (s *minInt64Heap) Push(x interface{}) { 49 *s = append(*s, x.(int64)) 50 } 51 52 func (s *minInt64Heap) Pop() interface{} { 53 if len(*s) == 0 { 54 return nil 55 } 56 q := (*s)[len(*s)-1] 57 *s = (*s)[:len(*s)-1] 58 return q 59 } 60 61 func NewInt64PriorityQueue(max bool, items ...int64) *PriorityQueue { 62 var h heap.Interface 63 if max { 64 t := maxInt64Heap(items) 65 h = &t 66 } else { 67 t := minInt64Heap(items) 68 h = &t 69 } 70 return NewPriorityQueue(h) 71 }