classSolution:defsecondGreaterElement(self, nums: List[int])-> List[int]:# 双单调栈# s存第一次,t存第二次
s, t =[],[]# 递减栈
ans =[-1]*len(nums)for i, x inenumerate(nums):# 第二个栈判断while t and nums[t[-1]]< x:
ans[t.pop()]= x
# 第一个栈判断
j =len(s)-1while j >=0and nums[s[j]]< x:
j -=1# 把第一个栈小于当前x的移到第二个栈
t += s[j +1:]del s[j +1:]# 加入当前的x对应的i
s.append(i)return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SortedDict解法
classSolution:defsecondGreaterElement(self, nums: List[int])-> List[int]:# 按从大到小排序
a =[(x, i)for i, x inenumerate(nums)]
a.sort(key =lambda it:(-it[0], it[1]))# sortedcontainersfrom sortedcontainers import SortedDict
sd = SortedDict()
k =2
ans =[-1]*len(a)for x, i in a:# 找到i对应的下标j
j = sd.bisect_right(i)if j + k -1<len(sd):
ans[i]= sd.peekitem(j + k -1)[1]
sd[i]= x # 存当前的值return ans