添加 0739.每日温度 go版本

添加 0739.每日温度 go版本
This commit is contained in:
X-shuffle
2021-06-13 20:56:40 +08:00
committed by GitHub
parent 59f577d535
commit 0e267fda96

View File

@ -214,6 +214,52 @@ Python
Go
> 暴力法
```go
func dailyTemperatures(temperatures []int) []int {
length:=len(temperatures)
res:=make([]int,length)
for i:=0;i<length;i++{
j:=i+1
if i==length-1{
res[i]=0
}
for j<length&&temperatures[i]>=temperatures[j]{//大于等于
j++
}
if j<length&&temperatures[i]<temperatures[j]{
res[i]=j-i
}
if j==length{
res[i]=0
}
}
return res
}
```
> 单调栈法
```go
func dailyTemperatures(temperatures []int) []int {
length:=len(temperatures)
res:=make([]int,length)
stack:=[]int{}
for i:=0;i<length;i++{
//如果当前栈中存在元素,新来的元素大于栈顶的元素,则计算差值并弹出栈顶元素
for len(stack)>0&&temperatures[i]>temperatures[stack[len(stack)-1]]{
res[stack[len(stack)-1]]=i-stack[len(stack)-1]//存放结果集
stack=stack[:len(stack)-1]//删除stack[len(stack)-1]的元素
}
//如果栈顶元素大于等于新来的元素则加入到栈中。当栈内元素个数为0时直接入栈
if len(stack)==0||temperatures[i]<=temperatures[stack[len(stack)-1]]{
stack = append(stack, i)
}
}
return res
}
```