[leetcode] 503. Next Greater Element II @ python

原题

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.
Note: The length of given array won’t exceed 10000.

解法1

先将nums重复一次, 然后我们遍历原来nums的长度, 用双指针法在新nums里寻找比现在指针更大的数字.
Time: O(3/2 * n^2)
Space: O(1)

代码

class Solution:
    def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        l = len(nums)
        nums = nums + nums
        res = []
        for i in range(l):
            curr, next = i, i+1
            while next < len(nums) and nums[next] <= nums[curr]:
                next += 1
            if next == len(nums):
                res.append(-1)
            else:
                res.append(nums[next])
        return res

解法2

初始化res, 假设所有的数字都没有找到Next Greater Element . 使用堆栈stack来存储已访问过但还没找到更大值的数字的索引, 遍历nums两遍, 如果走到i 点时发现i点的数字比stack中的数字要高, 则一直出栈, 更新res[i] 对应的数字.
注意index是遍历两个range(len(nums))的列表, 否则python 3会报错.
Time: O(n)
Space: O(1)

代码

class Solution:
    def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        stack = []
        res = [-1]*len(nums)
        
        for i in list(range(len(nums)))*2:
            while stack and nums[stack[-1]] < nums[i]:
                prev_i = stack.pop()
                res[prev_i] = nums[i]
            stack.append(i)            
            
        return res

你可能感兴趣的:(Leetcode)