Leetcode 503. Next Greater Element II

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
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
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/

以上是关于Leetcode 503. Next Greater Element II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 503. Next Greater Element II JAVA语言

Leetcode 503. Next Greater Element II

Leetcode 1019. Next Greater Node In Linked List

503. Next Greater Element II

503. Next Greater Element II

503. Next Greater Element II