defnextGreaterElement(nums): n = len(nums) result = [-1] * n # 默认值为-1 stack = [] # 递减栈 # 从左向右遍历 for i inrange(n): # 当前元素比栈顶元素大,说明找到了栈顶元素的下一个更大元素 while stack and nums[i] > nums[stack[-1]]: prev_index = stack.pop() result[prev_index] = nums[i] stack.append(i) return result
defincreasingStack(nums): stack = [] # 递增栈 for num in nums: # 保持栈的递增性 while stack and stack[-1] > num: stack.pop() stack.append(num)
3.2 递减栈模式
1 2 3 4 5 6 7
defdecreasingStack(nums): stack = [] # 递减栈 for num in nums: # 保持栈的递减性 while stack and stack[-1] < num: stack.pop() stack.append(num)
4. 实际应用示例
4.1 温度问题(每日温度)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defdailyTemperatures(temperatures): n = len(temperatures) result = [0] * n stack = [] # 存储索引的递减栈 for i, temp inenumerate(temperatures): while stack and temp > temperatures[stack[-1]]: prev_day = stack.pop() result[prev_day] = i - prev_day stack.append(i) return result
defnextGreaterElements(nums): n = len(nums) result = [-1] * n stack = [] # 递减栈 # 遍历两次数组 for i inrange(n * 2): index = i % n while stack and nums[index] > nums[stack[-1]]: result[stack.pop()] = nums[index] if i < n: # 只在第一次遍历时入栈 stack.append(index) return result