Leetcode 503. Next Greater Element II

2021-07-15 14:08:00 浏览数 (1)

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞