Leetcode - Rotate List
Leetcode - Inorder Successor in BST

Leetcode - Next Greater Element II

violet posted @ Mar 24, 2020 10:26:36 AM in 算法 with tags Algorithm Golang array , 237 阅读

https://leetcode.com/problems/next-greater-element-ii/

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

Example 1:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number; 
The second 1's next greater number needs to search circularly, which is also 2.

 

func nextGreaterElements(nums []int) []int {
    result := make([]int, len(nums))
    stack := []int{}
    size := len(nums)
    for i := size-1; i >= 0; i-- {
        stack = append(stack, i)
    }
    for i := size-1; i >= 0; i-- {
        result[i] = -1
        for len(stack) != 0 && nums[stack[len(stack)-1]] <= nums[i] {
            stack = stack[:len(stack)-1]
        }
        if len(stack) != 0 {
            result[i] = nums[stack[len(stack)-1]]
        }
        stack = append(stack, i)
    }
    
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter