659.split-array-into-consecutive-subsequences.go 892 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. type minHeap []int // Stores the length only
  2. func (h minHeap) Len() int { return len(h) }
  3. func (h minHeap) Less(i, j int) bool { return h[i] < h[j] }
  4. func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  5. func (h *minHeap) Push(x interface{}) {
  6. *h = append(*h, x.(int))
  7. }
  8. func (h *minHeap) Pop() interface{} {
  9. l := len(*h)
  10. x := (*h)[l-1]
  11. *h = (*h)[0 : l-1]
  12. return x
  13. }
  14. var m map[int]*minHeap
  15. func isPossible(nums []int) bool {
  16. m = make(map[int]*minHeap)
  17. for _, num := range nums {
  18. last := helper(num - 1)
  19. l := 0
  20. if last.Len() != 0 {
  21. l = heap.Pop(last).(int)
  22. }
  23. curr := helper(num)
  24. heap.Push(curr, l+1)
  25. }
  26. for _, v := range m {
  27. h := *v
  28. for _, l := range h {
  29. if l < 3 {
  30. return false
  31. }
  32. }
  33. }
  34. return true
  35. }
  36. func helper(num int) *minHeap {
  37. if h, ok := m[num]; ok {
  38. return h
  39. } else {
  40. var h minHeap
  41. m[num] = &h
  42. return &h
  43. }
  44. }