python code


  • 0
    T

    class Solution(object):
    def nextGreaterElements(self, nums):

        length = len(nums)
    
        cache = {}
    
        for idx in range(length)[::-1]:
    
            v = nums[idx]
    
            IsFind = 0
    
            dis = 1
    
            while dis<length:
    
                idj = (idx+dis)%length
    
                if nums[idj]>v:
                    cache[idx] = (nums[idj],dis)
                    IsFind = 1
                    dis = 1e100
                else:
                    if idj in cache:
                        c = cache[idj][0]
                        if c> v:
    
                            if cache[idj][1] is None:
                                cache[idx] = (-1,None)
                            else:
                                cache[idx] = (c,cache[idj][1]+dis)
                            IsFind = 1
                            dis = 1e100
                        else:
                            if cache[idj][1]:
                                dis += cache[idj][1]
                            else:
                                cache[idx] = (-1,None)
                                IsFind = 1
                                dis =1e100
    
    
                    dis+=1
            if not IsFind:
                cache[idx] = (-1,None)
    
        return [one[0] for one in cache.values()]

Log in to reply
 

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