Ruby solution using stack


  • 0
    B
    def next_greater_elements(nums)
        n = nums.size
        res = []
        stack = []
        (n-1).downto(0) do |i|
            stack << i
        end
        (n-1).downto(0) do |i|
            res[i] = -1
            stack.pop while !stack.empty? && nums[stack[-1]] <= nums[i]
            res[i] = nums[stack[-1]] if !stack.empty?
            stack << i
        end
        res
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.