Leetcode 503. Next Greater Element II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Next Greater Element II

2. Solution

解析:Version 1,由于元素不是唯一的,需要循环查找,因此先将nums复制一遍,通过循环每次都查找当前元素之后的n-1位数字。Version 2通过使用栈来寻找满足条件的结果,栈中保持是数字的索引位置,由于需要循环查找,因此需要查找两次nums,并且第二次查找不需要保持数字索引。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
nums = nums + nums
result = []
for i in range(n):
flag = True
for j in range(i+1, i+n):
if nums[j] > nums[i]:
result.append(nums[j])
flag = False
break
if flag:
result.append(-1)
return result
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [-1] * n
stack = []
for index, num in enumerate(nums):
while stack and nums[stack[-1]] < num:
result[stack.pop()] = num
stack.append(index)

for num in nums[:stack[-1]]:
while stack and nums[stack[-1]] < num:
result[stack.pop()] = num
return result

Reference

  1. https://leetcode.com/problems/next-greater-element-ii/
如果有收获,可以请我喝杯咖啡!