1. 最小栈
155. min-stack
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
分析
单纯地用数组实现一个栈很容易,但要实现常数时间检索到最小值就麻烦了;
使用最小栈,每个元素是截至目前的最小值
假设数据栈内容[3, 4, 2, 5],最小栈相应的内容[3, 3, 2, 2]
"""
self.data = []
self.mins = []
self.top_idx = -1
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.data.append(x)
if not self.mins:
self.mins.append(x)
else:
self.mins.append(min(x, self.mins[self.top_idx]))
self.top_idx += 1
def pop(self):
"""
:rtype: None
"""
x = self.data.pop()
self.mins.pop()
self.top_idx -= 1
return x
def top(self):
"""
:rtype: int
"""
return self.data[self.top_idx]
def getMin(self):
"""
:rtype: int
"""
return self.mins[self.top_idx]
2. 有效的括号
20. valid-parentheses
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
解法
使用栈,左括号代表入栈,右括号代表出栈
如果要出栈,出栈的元素要与当前元素匹配
最终栈要为空
"""
if len(s) % 2 == 1:
return False
d = {'(': ')', '{': '}', '[': ']'}
stack = []
for char in s:
if char in d:
stack.append(char)
else:
if not stack or d[stack.pop()] != char:
return False
return True if not stack else False
3. 每日温度
739. daily-temperatures
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
笨办法
暴力法
聪明办法
使用单调栈缓存递减的温度
栈内元素的温度从栈底往栈顶呈递减趋势, 栈内元素需要存放数组下标
将当前元素与栈顶元素对比, 当前元素大, 则出栈输出结果; 否则, 入栈
https://leetcode-cn.com/problems/daily-temperatures/solution/mei-ri-wen-du-by-leetcode-solution/
"""
result = [0] * len(T)
stack = []
for i, t in enumerate(T):
while stack:
if t <= stack[-1][1]:
stack.append((i, t))
break
else:
top_t = stack.pop()
result[top_t[0]] = i - top_t[0]
else:
stack.append((i, t))
return result