本文主要是介绍503.下一个更大元II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#暴力搜索
class Solution:def nextGreaterElements(self, nums: List[int]) -> List[int]:n = len(nums)res = [-1]*nfor i in range(n):for j in range(i+1,i+n):if nums[j%n] > nums[i]:res[i] = nums[j%n]breakreturn res
class Solution:def nextGreaterElements(self, nums: List[int]) -> List[int]:#单调栈+哈希n = len(nums)res = [-1]*(n)stk = [0] for i in range(1,2*n):if nums[i%n] <= nums[stk[-1]]:stk.append(i%n)else:while len(stk) != 0 and nums[i%n] > nums[stk[-1]]:res[stk[-1]] = nums[i%n]stk.pop()stk.append(i%n)return res
这篇关于503.下一个更大元II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!