739. 每日溫度 - 力扣(LeetCode)
while要把stack的判斷放在前面,否則stack[-1]可能報錯
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
155. 最小棧 - 力扣(LeetCode)
雙棧,空間換時間,單獨維護一個最小棧,最小棧每一個位置對應棧那個位置的最小值
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]
739. 每日溫度 - 力扣(LeetCode)
while要把stack的判斷放在前面,否則stack[-1]可能報錯
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
155. 最小棧 - 力扣(LeetCode)
雙棧,空間換時間,單獨維護一個最小棧,最小棧每一個位置對應棧那個位置的最小值
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]