-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path739-daily-temperatures.go
65 lines (53 loc) · 1.08 KB
/
739-daily-temperatures.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Link:
import (
"container/heap"
)
type Item struct {
Index int
Val int
}
type PQueue []Item
func (pq *PQueue) Push(x interface{}) {
*pq = append(*pq, x.(Item))
}
func (pq PQueue) Peek() interface{} {
return pq[0]
}
func (pq *PQueue) Pop() interface{} {
n := len(*pq)
item := (*pq)[n-1]
*pq = (*pq)[:n-1]
return item
}
func (pq PQueue) Less(i,j int) bool {
return pq[i].Val < pq[j].Val
}
func (pq PQueue) Len() int {
return len(pq)
}
func (pq PQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func dailyTemperatures(T []int) []int {
if len(T) == 0 {
return []int{}
}
pq := make(PQueue, 0)
heap.Init(&pq)
ans := make([]int, len(T))
for i, t := range T {
for pq.Len() > 0 {
front := pq.Peek().(Item)
if front.Val < t {
ans[front.Index] = i-front.Index
heap.Pop(&pq)
} else {
break
}
}
heap.Push(&pq, Item{i, t})
}
return ans
}
// Time complexity: O(NlogN)
// Space complexity: O(N)