0%

LeetCode-503

题目

结果

代码

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
func nextGreaterElements(nums []int) []int {
if len(nums) == 0 {
return []int{}
}
_max := nums[0]
for _, v := range nums {
_max = max(_max, v)
}
ans := make([]int, 0, len(nums))
for i, v := range nums {
if v == _max {
ans = append(ans, -1)
continue
}
for j := i; ; {
if nums[j] > v {
ans = append(ans, nums[j])
break
}
j++
if j >= len(nums) {
j = 0
}
}
}
return ans
}

func max(x, y int) int {
if x > y {
return x
}
return y
}

复杂度

时间复杂度:O(N)

空间复杂度:O(1)