生活随笔
收集整理的這篇文章主要介紹了
数据结构 - 单调栈、单调队列
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
單調(diào)棧:每日溫度
- 請(qǐng)根據(jù)每日 氣溫 列表 temperatures ,請(qǐng)計(jì)算在每一天需要等幾天才會(huì)有更高的溫度。如果氣溫在這之后都不會(huì)升高,請(qǐng)?jiān)谠撐恢糜?0 來代替
- 單調(diào)?;局惶幚鞱GE問題(Next GreaterElement)。對(duì)序列中每個(gè)元素,找到下一個(gè)比它大的元素。(“下一個(gè)”可以換成“上一個(gè)”,“大”也可以換成“小”)
class Solution(object):def dailyTemperatures(self
, temperatures
):""":type temperatures: List[int]:rtype: List[int]"""length
= len(temperatures
)res
= [0 for _
in range(length
)]stack
= [] for i
in range(length
):t
= temperatures
[i
]while (len(stack
) > 0 and temperatures
[stack
[-1]] < t
):res
[stack
[-1]] = i
- stack
[-1]stack
.pop
()stack
.append
(i
)return res
單調(diào)隊(duì)列:滑動(dòng)窗口的最大值
"""
用一個(gè)queue(滑動(dòng)窗口,先入先出)和一個(gè)deque實(shí)現(xiàn)
queue負(fù)責(zé)push和pop,deque用來存放最大值
1. 如果新的value大于deque尾端的值,那么deque一直進(jìn)行pop_back操作,直到尾端的值大于等于value 或者為空,再將value壓入deque的尾部
2. 每次取max_value,返回deque首部的值
3. 當(dāng)que進(jìn)行pop操作時(shí),如果que首部的值等于deque首部的值,那么deque同樣需要進(jìn)行pop_front操作
"""
class Solution(object):def maxSlidingWindow(self
, nums
, k
):""":type nums: List[int]:type k: int:rtype: List[int]"""desc_q
= [] for i
in range(k
):while (desc_q
and desc_q
[-1] < nums
[i
]):desc_q
.pop
()desc_q
.append
(nums
[i
])res
= [desc_q
[0]]for i
in range(k
, length
):in_num
= nums
[i
] out_num
= nums
[i
- k
] if out_num
== desc_q
[0]: desc_q
.pop
(0)while (desc_q
and desc_q
[-1] < in_num
):desc_q
.pop
()desc_q
.append
(in_num
)res
.append
(desc_q
[0])return res
總結(jié)
以上是生活随笔為你收集整理的数据结构 - 单调栈、单调队列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。