mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0739.每日温度 go版本
添加 0739.每日温度 go版本
This commit is contained in:
@ -214,6 +214,52 @@ Python:
|
|||||||
|
|
||||||
Go:
|
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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user