-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution496.go
More file actions
63 lines (53 loc) · 1.25 KB
/
Copy pathsolution496.go
File metadata and controls
63 lines (53 loc) · 1.25 KB
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
package solution496
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/496
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_nextGreaterElementV2
Benchmark_nextGreaterElementV2-24 8935968 112.7 ns/op 0 B/op 0 allocs/op
PASS
*/
func nextGreaterElementV2(nums1 []int, nums2 []int) []int {
indexes := make(map[int]int)
for i := 0; i < len(nums2); i++ {
indexes[nums2[i]] = i
}
for i := 0; i < len(nums1); i++ {
num := nums1[i]
idx := indexes[num]
highest := -1
for j := idx; j < len(nums2); j++ {
if nums2[j] > num {
highest = nums2[j]
break
}
}
nums1[i] = highest
}
return nums1
}
func nextGreaterElementV1(nums1 []int, nums2 []int) []int {
indexes := make(map[int]int)
for i := 0; i < len(nums2); i++ {
indexes[nums2[i]] = i
}
nextGreater := make(map[int]int)
stack := make([]int, len(nums1))
for i := 0; i < len(nums2); i++ {
for len(stack) > 0 && nums2[i] > stack[len(stack)-1] {
nextGreater[stack[len(stack)-1]] = nums2[i]
stack = stack[:len(stack)-1]
}
stack = append(stack, nums2[i])
}
output := make([]int, len(nums1))
for i, num := range nums1 {
if val, found := nextGreater[num]; found {
output[i] = val
} else {
output[i] = -1
}
}
return output
}