确定是递增栈还是递减栈,快速解决问题:
while 元素未遍历完:
while 栈不空 and 当前元素>栈顶元素:
出栈
把当前元素入栈
变形
stackA = [0] * 6
stackB = [0] * 6
topA = -1
topB = -1
d = [5, 9, 4, 8, 7, 2]
for i in range(len(d)):
while topA != -1 and d[i] < stackA[topA]:
topB += 1
stackB[topB] = stackA[topA]
topA -= 1
topA += 1
stackA[topA] = d[i]
while topB != -1:
topA += 1
stackA[topA] = stackB[topB]
topB -= 1
程序执行过程当中,变量topB的最大值为 A、1 B、2 C、3 D、4
【例】有如下Python 程序段:
num = "1433218"
k = 3
n = len(num)
ans = ""
s = [""] * n
top = -1
for i in num:
while k > 0 and top > -1 and s[top] > i:
top -= 1
k -= 1
top += 1
s[top] = i
if k > 0:
top -= k
while top > -1:
ans = s[top] + ans
top -= 1
print(ans)
A、1321 B、1322 C、3121 D、1218
练习:
tmps = [32, 28, 26, 29]
n = len(tmps)
top = -1
ans = [0] * n
stk = [-1] * n
for i in range(n):
t = tmps[i]
while top > -1 and t > tmps[stk[top]]:
d = stk[top]
top -= 1
ans[d] = i - d
top += 1
stk[top] = i
print(ans)
A、[1, 0, 0, 1] B、[1, 1, 0, 0] C、[0, 2, 1, 0] D、[0, 1, 2, 0]
答案:
D
D
C
由代码可知,比栈顶大的t值出栈,且计算与栈顶之间索引差值。i=0,1,2时,while均不执行,stk=[0,1,2];i=3时,t=29,执行while使得stk出栈两次,分别d=2,1,所以ans[2]=3-2=1,ans[1]=3-1=2,选C。
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com