剑指offer-找出数组中每个数右边第一个比它大的元素--python

暴力破解就不多加叙述了,主要是记一下单调栈解法。时间复杂度o(n)

思想:
1.如果tmp是空的那么就进栈
2.tmp不空,并且a[i]>a[tmp中的顶部一个位置],就弹出,并且res【这个位置】=a【i】,否则就进栈,

a=[1,2,4,6,3,8]
tmp=[0]#临时保存位置
res=[]#结果
i=1
while i<len(a):
	if len(tmp)!=0 and a[i]>a[tmp[-1]]:
		res[tmp.pop()]=a[i]
	else:
		tmp.append(i)
		i+=1
return res

参考:https://blog.csdn.net/smileiam/article/details/88732245

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104309737
今日推荐