• 代码随想录算法训练营Day58 | 单调栈(1/3) LeetCode 739. 每日温度 496.下一个更大元素 I


    动态规划结束了,来到最后一块内容:单调栈了,一共就三天的内容。

    1. 单调栈基本知识

    1.1 什么情况下使用单调栈呢?

    通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。时间复杂度为O(n)。

    单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是整个数组只需要遍历一次。

    更直白来说,就是用一个栈来记录我们遍历过的元素,因为我们遍历数组的时候,我们不知道之前都遍历了哪些元素,以至于遍历一个元素找不到是不是之前遍历过一个更小的,所以我们需要用一个容器(这里用单调栈)来记录我们遍历过的元素。

    1.2 使用单调栈主要有三个判断条件。
    • 当前遍历的元素T[i]小于栈顶元素T[st.top()]的情况
    • 当前遍历的元素T[i]等于栈顶元素T[st.top()]的情况
    • 当前遍历的元素T[i]大于栈顶元素T[st.top()]的情况

    下面进入到练习:

    第一题

    739. Daily Temperatures

    Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

    首先想到的还是Brute Force,两层for循环,把至少需要等待的天数就搜出来了。时间复杂度是O(n^2)。

    这是一道应用单调栈的题,分析的时候,要涵盖以下三种情况:

    • 情况一:当前遍历的元素T[i]小于栈顶元素T[st.top()]的情况
    • 情况二:当前遍历的元素T[i]等于栈顶元素T[st.top()]的情况
    • 情况三:当前遍历的元素T[i]大于栈顶元素T[st.top()]的情况
    1. class Solution:
    2. def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    3. answer = [0]*len(temperatures)
    4. stack = [0]
    5. for i in range(1,len(temperatures)):
    6. if temperatures[i]<=temperatures[stack[-1]]:
    7. stack.append(i)
    8. else:
    9. while len(stack) != 0 and temperatures[i]>temperatures[stack[-1]]:
    10. answer[stack[-1]]=i-stack[-1]
    11. stack.pop()
    12. stack.append(i)
    13. return answer

    第二题

    496. Next Greater Element I

    The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

    You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

    For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

    Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

    要分析如下三种情况,

    情况一:当前遍历的元素T[i]小于栈顶元素T[st.top()]的情况

            此时满足递增栈(栈头到栈底的顺序),所以直接入栈。

    情况二:当前遍历的元素T[i]等于栈顶元素T[st.top()]的情况

            如果相等的话,依然直接入栈,因为我们要求的是右边第一个比自己大的元素,而不是大于等于!

    情况三:当前遍历的元素T[i]大于栈顶元素T[st.top()]的情况

            此时如果入栈就不满足递增栈了,这也是找到右边第一个比自己大的元素的时候。

    判断栈顶元素是否在nums1里出现过,(注意栈里的元素是nums2的元素),如果出现过,开始记录结果。

    记录结果这块逻辑有一点小绕,要清楚,此时栈顶元素在nums2数组中右面第一个大的元素是nums2[i](即当前遍历元素)。

    1. class Solution:
    2. def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
    3. result = [-1]*len(nums1)
    4. stack = [0]
    5. for i in range(1,len(nums2)):
    6. if nums2[i]<=nums2[stack[-1]]:
    7. stack.append(i)
    8. else:
    9. while len(stack)!=0 and nums2[i]>nums2[stack[-1]]:
    10. if nums2[stack[-1]] in nums1:
    11. index = nums1.index(nums2[stack[-1]])
    12. result[index]=nums2[i]
    13. stack.pop()
    14. stack.append(i)
    15. return result

  • 相关阅读:
    Freeswitch 常用命令
    【快应用】input组件的输入框弹出后,如何点击其他地方后失去焦点,并收起键盘
    在Express框架使用ORM模型访问关系型数据库
    java计算机毕业设计学生健康信息管理源程序+mysql+系统+lw文档+远程调试
    【MySQL入门】第三话 · MySQL中常见的数据类型
    如何训练专属的OCR文字识别模型
    golang_iota
    redis学习四redis消息订阅、pipeline、事务、modules、布隆过滤器、缓存LRU
    2023NOIP A层联测19 多边形
    网络面试-0x03http有哪些常见的请求头以及作用
  • 原文地址:https://blog.csdn.net/Hanzq1997/article/details/133247206