-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
51 lines (44 loc) · 1.14 KB
/
stack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#==================================================
#==> Title: Stack
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/15/2021
#==================================================
"""
Next Greater Element
in: [2,1,2,4,3]
out: [4,2,4,-1,-1]
"""
def nextGreaterElement(nums):
n = len(nums)
res = [-1] * n
stack = []
for i in range(n-1, -1, -1):
while len(stack) != 0 and nums[i] >= nums[stack[-1]]:
stack.pop()
if len(stack) != 0:
res[i] = nums[stack[-1]]
stack.append(i)
return res
"""
循环数组
in: [2,1,2,4,3]
out: [4,2,4,-1,4]
"""
def nextGreaterElementCircle(nums):
n = len(nums)
res = [-1] * n
stack = []
for i in range(2*n-1, -1, -1):
while len(stack) != 0 and nums[i % n] >= nums[stack[-1]]:
stack.pop()
if len(stack) != 0:
res[i % n] = nums[stack[-1]]
stack.append(i % n)
return res
nums = [2,1,2,4,3]
# Next Greater Element
print(nextGreaterElement(nums))
# 循环数组
print(nextGreaterElementCircle(nums))