题解 | 栈和排序

栈和排序

https://www.nowcoder.com/practice/b10a7ac681e9429e89a6a510e5799647

'''如果栈顶元素大于 第i项到第n项的最大值,说明如果让这个元素出栈此时的字典序肯定会更大。
如果栈顶元素小于 第i项到第n项的最大值,那就让该元素入栈,因为让大的先出栈总总能保证字典序最大'''

n = int(input())
p = list(map(int,input().split()))
imax = p.index(max(p))
pre = p[:imax]
aft = p[imax+1:]
s = [p.pop(imax)]
while len(aft)>0:
    a = aft.pop(0)
    if len(aft)==0:
        s += [a]
    else:
        if a>max(aft):
            s += [a]
        else:
            pre += [a]
s += pre[::-1]
print(' '.join(map(str,s)))

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务