
while要把stack的判断放在前面,否则stack[-1]可能报错
python
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
#单调栈里存元素的话还要返回去得下标
#直接存下标就没有这个问题
#单调栈存放遍历过但没结果的数
ans=[0]*len(temperatures)
stack=[]
for i in range(len(temperatures)):
if not stack:
stack.append(i)
elif temperatures[i]>temperatures[stack[-1]]:
#while temperatures[i]>temperatures[stack[-1]] and stack:
while stack and temperatures[i]>temperatures[stack[-1]]:
ans[stack[-1]]=i-stack[-1]
stack.pop()
stack.append(i)
else:
stack.append(i)
return ans

双栈,空间换时间,单独维护一个最小栈,最小栈每一个位置对应栈那个位置的最小值
python
class MinStack(object):
def __init__(self):
#minstack栈顶是维护和stack相同长度目前为止最小的元素
self.stack=[]
self.minstack=[]
def push(self, val):
"""
:type val: int
:rtype: None
"""
if not self.minstack:
self.minstack.append(val)
else:
self.minstack.append(min(self.minstack[-1],val))
self.stack.append(val)
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minstack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minstack[-1]
while要把stack的判断放在前面,否则stack[-1]可能报错
python
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
#单调栈里存元素的话还要返回去得下标
#直接存下标就没有这个问题
#单调栈存放遍历过但没结果的数
ans=[0]*len(temperatures)
stack=[]
for i in range(len(temperatures)):
if not stack:
stack.append(i)
elif temperatures[i]>temperatures[stack[-1]]:
#while temperatures[i]>temperatures[stack[-1]] and stack:
while stack and temperatures[i]>temperatures[stack[-1]]:
ans[stack[-1]]=i-stack[-1]
stack.pop()
stack.append(i)
else:
stack.append(i)
return ans

双栈,空间换时间,单独维护一个最小栈,最小栈每一个位置对应栈那个位置的最小值
python
class MinStack(object):
def __init__(self):
#minstack栈顶是维护和stack相同长度目前为止最小的元素
self.stack=[]
self.minstack=[]
def push(self, val):
"""
:type val: int
:rtype: None
"""
if not self.minstack:
self.minstack.append(val)
else:
self.minstack.append(min(self.minstack[-1],val))
self.stack.append(val)
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minstack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minstack[-1]