模拟
解题思路:通过题目描述和案例找到规律,然后模拟案例的行为即可。
例子
一、验证栈序列
前提:已知序列中所有的数字都是不同的。
思路:使用栈模拟。
1、如果这个弹出的数字 poped[i]和栈顶数字是相等的,那么栈就要把已有的数字弹出来。
2、如果栈是空的,或者栈顶数字 poped[i]和栈顶数字不等,那么我们应该把 pushed[i]数字一直往栈里放,直到与poped[i]相等为止。
3、最后,如果栈是空的,说明栈的入栈序列能得到这个出栈序列。
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
l = len(pushed)
stack = []
n = 0
for i in range(l):
if stack and popped[i] == stack[-1]:
stack.pop()
else:
# 向stack里面放数据,如果相等跳过该数
while n < l and popped[i] != pushed[n]:
stack.append(pushed[n])
n += 1
n += 1
return not stack
二、螺旋矩阵
顺时针打印矩阵的顺序是 “从左向右、从上向下、从右向左、从下向上” 循环。
因此,考虑设定矩阵的 “左、上、右、下” 四个边界,模拟以上矩阵遍历顺序。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if not matrix:
return res
l, r, t, b = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
while True:
for i in range(l, r+1):
res.append(matrix[t][i])
t += 1
if t > b: break
for i in range(t, b+1):
res.append(matrix[i][r])
r -= 1
if l > r: break
for i in range(r, l-1, -1):
res.append(matrix[b][i])
b -= 1
if t > b: break
for i in range(b, t-1, -1):
res.append(matrix[i][l])
l += 1
if l > r: break
return res
三、最小栈
思路: 辅助一个变量来存储最小值。
class MinStack:
def __init__(self):
self.stack = []
def push(self, val: int) -> None:
if not self.stack:
self.stack.append((val, val))
else:
self.stack.append((val, min(self.stack[-1][1], val)))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
return self.stack[-1][1]
四、丑数
264. 丑数 II
给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是质因子只包含 2、3 和 5 的正整数。
示例 1:
输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
示例 2:
输入:n = 1
输出:1
解释:1 通常被视为丑数。
class Solution:
def nthUglyNumber(self, n: int) -> int:
res, a, b, c = [1]*n, 0, 0, 0
for i in range(1, n):
na, nb, nc = res[a] * 2, res[b] * 3, res[c] * 5
min_n = min(na, nb, nc)
if min_n == na:
a += 1
if min_n == nb:
b += 1
if min_n == nc:
c += 1
res[i] = min_n
return res[-1]
参考
https://leetcode.cn/problems/validate-stack-sequences/solutions/1788021/fu-xue-ming-zhu-by-fuxuemingzhu-iafi/
https://leetcode.cn/problems/spiral-matrix/solutions/2362055/54-luo-xuan-ju-zhen-mo-ni-qing-xi-tu-jie-juvi/