topk.go 705 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package stat
  2. import "container/heap"
  3. type taskHeap []Task
  4. func (h *taskHeap) Len() int {
  5. return len(*h)
  6. }
  7. func (h *taskHeap) Less(i, j int) bool {
  8. return (*h)[i].Duration < (*h)[j].Duration
  9. }
  10. func (h *taskHeap) Swap(i, j int) {
  11. (*h)[i], (*h)[j] = (*h)[j], (*h)[i]
  12. }
  13. func (h *taskHeap) Push(x interface{}) {
  14. *h = append(*h, x.(Task))
  15. }
  16. func (h *taskHeap) Pop() interface{} {
  17. old := *h
  18. n := len(old)
  19. x := old[n-1]
  20. *h = old[0 : n-1]
  21. return x
  22. }
  23. func topK(all []Task, k int) []Task {
  24. h := new(taskHeap)
  25. heap.Init(h)
  26. for _, each := range all {
  27. if h.Len() < k {
  28. heap.Push(h, each)
  29. } else if (*h)[0].Duration < each.Duration {
  30. heap.Pop(h)
  31. heap.Push(h, each)
  32. }
  33. }
  34. return *h
  35. }