We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 94c8760 commit 7bb7f9bCopy full SHA for 7bb7f9b
scripts/algorithms/N/Next Greater Element II/Next Greater Element II.py
@@ -1,23 +1,14 @@
1
+// Runtime: 151 ms (Top 99.29%) | Memory: 19.30 MB (Top 5.84%)
2
+
3
class Solution:
4
def nextGreaterElements(self, nums: List[int]) -> List[int]:
- t=len(nums)
- nums+=nums
5
- l=[-1]*len(nums)
6
- d={}
7
- stack=[0]
8
- for x in range(1,len(nums)):
9
- #print(x)
10
- if nums[x]>nums[stack[-1]]:
11
- while nums[x]>nums[stack[-1]] :
12
- l[stack[-1]]=nums[x]
13
- stack.pop()
14
- if stack==[]:
15
- break
16
- #print(l)
17
- stack.append(x)
18
-
19
- else:
20
21
- return l[:t]
22
23
+ st = []
+ n = len(nums)
+ ans = [-1] * n
+ for i in range(2*n-1, -1, -1):
+ while st and st[-1] <= nums[i%n]:
+ st.pop()
+ if st and i < n:
+ ans[i] = st[-1]
+ st.append(nums[i%n])
+ return ans
0 commit comments