递减栈

任意一个元素找左边和右边第一个比自己大/小的位置,用单调栈。

  • 单调栈主要可以用来解决区间最值问题
  • 比如求一个一维数组的中某一个数的右边第一个比他大的元素或者元素下标。

leetcode参考题目

    1. Largest Rectangle in Histogram
    1. Maximal Rectangle.
    1. Next Greater Element I
  • 739.Daily Temperatures 日常温度
    1. Next Greater Node In Linked List
    1. Next Greater Element II
#496. Next Greater Element I
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        
        # index = [-1] * len(nums1)
        # res = [-1] * len(nums1)
        # for i in range(len(nums1)):
        #     for j in range(len(nums2)):
        #         if nums1[i] == nums2[j]:
        #             index[i] = j
        # print(index)
        # for i in range(len(nums1)):
        #     for j in range(index[i],len(nums2)): 
        #            if nums2[j]>nums1[i]:
        #                 res[i] = nums2[j]
        #                 break
        # return res
        #这道题的简单之处在于数组中没有重复的元素
        res = []
        stack = []
        dic = dict()
        for item in nums2: 
            while(len(stack)>0 and stack[-1]<item):
                dic[stack.pop()] = item  
            stack.append(item)
        for i in range(len(nums1)):
            res.append(-1)
            if nums1[i] in dic:
                res[i] = dic[nums1[i]]
        return res   
#1019. Next Greater Node In Linked List
#注意链表中的元素有可能有相同的元素值
class Solution:
    def nextLargerNodes(self, head: ListNode) -> List[int]: 
        res = []
        #声明一个栈(以列表来代替)
        stack = []
        p = head
        count = 0
        while(p):
            res.append(0)
            while(len(stack)>0 and stack[-1][1] < p.val):
                res[stack.pop()[0]] = p.val
            stack.append((count,p.val))
            p = p.next
            count+=1
        return res
#类似题目503. Next Greater Element II
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.
#这道题主要是一个循环的数组,主要是在循环完一遍之后,再针对栈中剩下的元素,在对原数组进行一次扫描,直到栈为空
class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        res = []
        #声明一个栈(以列表来代替)
        stack = []
        count = 0
        # for count in range(len(nums)):
        while(count<len(nums)):
            res.append(-1)
            while(len(stack)>0 and stack[-1][1] < nums[count]):
                res[stack.pop()[0]] = nums[count]
            stack.append((count,nums[count]))
            count+=1  
        #此时栈中所剩下的元素就是等待被循环的元素
        count = 0
        for item in nums:
            while(len(stack)>0 and stack[-1][1] < nums[count]):
                res[stack.pop()[0]] = nums[count]
            count+=1
        return res
单调是一种常用的数据结构,用于解决一类特定的问题,其中最常见的问题是找到数组中每个元素的下一个更大或更小的元素。在Codeforces编程竞赛中,单调经常被用于解决一些与数组相关的问题。 下面是单调的一般思路: 1. 创建一个空。 2. 从左到右遍历数组元素。 3. 对于每个元素,将其与顶元素进行比较。 - 如果当前元素小于等于顶元素,则将当前元素入。 - 如果当前元素大于顶元素,则将顶元素弹出,并将当前元素入。 4. 重复步骤3,直到遍历完所有元素。 这样,最后剩下的中元素就是没有下一个更大或更小元素的元素。在使用单调求解具体问题时,我们可以根据需要进行一些特定的操作。 例如,如果要找到一个数组中每个元素的下一个更大的元素,可以使用单调递减。具体操作如下: 1. 创建一个空和一个空结果数组。 2. 从左到右遍历数组元素。 3. 对于每个元素,将其与顶元素进行比较。 - 如果当前元素小于等于顶元素,则将当前元素入。 - 如果当前元素大于顶元素,则将顶元素弹出,并将其在结果数组中的位置记录为当前元素的下一个更大元素的索引。 4. 将当前元素入。 5. 重复步骤3和4,直到遍历完所有元素。 6. 结果数组中没有下一个更大元素的位置,可以设置为-1。 以下是一个使用单调递减求解下一个更大元素问题的示例代码: ```cpp #include <iostream> #include <stack> #include <vector> std::vector<int> nextGreaterElement(std::vector<int>& nums) { int n = nums.size(); std::vector<int> result(n, -1); std::stack<int> stack; for (int i = 0; i < n; i++) { while (!stack.empty() && nums[i] > nums[stack.top()]) { result[stack.top()] = i; stack.pop(); } stack.push(i); } return result; } int main() { std::vector<int> nums = {1,3, 2, 4, 5, 1}; std::vector<int> result = nextGreaterElement(nums); for (int i = 0; i < result.size(); i++) { std::cout << "Next greater element for " << nums[i] << ": "; if (result[i] != -1) { std::cout << nums[result[i]]; } else { std::cout << "None"; } std::cout << std::endl; } return 0; } ``` 以上代码将输出: ``` Next greater element for 1: 3 Next greater element for 3: 4 Next greater element for 2: 4 Next greater element for 4: 5 Next greater element for 5: None Next greater element for 1: None ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值