代码训练营第60天:单调栈part01|leetcode739 每日温度|leetcode496 下一个更大元素

编程入门 行业动态 更新时间:2024-10-18 01:37:25

代码训练营第60天:单调栈part01|leetcode739 每日温度|leetcode496 下一个<a href=https://www.elefans.com/category/jswz/34/1759175.html style=更大元素"/>

代码训练营第60天:单调栈part01|leetcode739 每日温度|leetcode496 下一个更大元素

leetcode739:每日温度

文章讲解:leetcode739

leetcode496:下一个更大元素

文章讲解:leetcode496​​​​​​​

1,leetcode739 每日温度

那有同学就问了,我怎么能想到用单调栈呢? 什么时候用单调栈呢?

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

例如本题其实就是找找到一个元素右边第一个比自己大的元素,此时就应该想到用单调栈了。

那么单调栈的原理是什么呢?为什么时间复杂度是O(n)就可以找到每一个元素的右边第一个比它大的元素位置呢?

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

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

class Solution {
public:vector<int> dailyTemperatures(vector<int>& T) {// 递增栈stack<int> st;vector<int> result(T.size(), 0);st.push(0);for (int i = 1; i < T.size(); i++) {if (T[i] < T[st.top()]) {                       // 情况一st.push(i);} else if (T[i] == T[st.top()]) {               // 情况二st.push(i);} else {while (!st.empty() && T[i] > T[st.top()]) { // 情况三result[st.top()] = i - st.top();st.pop();}st.push(i);}}return result;}
};

其实说白了就是确保栈中的元素是有序的,利用这一性质去做区间判断

2,leetcode496 下一个更大元素

class Solution {
public:vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {stack<int> st;vector<int> result(nums1.size(), -1);if (nums1.size() == 0) return result;unordered_map<int, int> umap; for (int i = 0; i < nums1.size(); i++) {umap[nums1[i]] = i;}st.push(0);for (int i = 1; i < nums2.size(); i++) {if (nums2[i] < nums2[st.top()]) {          st.push(i);} else if (nums2[i] == nums2[st.top()]) {   st.push(i);} else {                                   while (!st.empty() && nums2[i] > nums2[st.top()]) {if (umap.count(nums2[st.top()]) > 0) { int index = umap[nums2[st.top()]];result[index] = nums2[i];}st.pop();}st.push(i);}}return result;}
};

与上面那道题几乎是一致的,就是把一个数组转化到一个哈希表中,就变成一个正常的单调栈做法了。

更多推荐

代码训练营第60天:单调栈part01|leetcode739 每日温度|leetcode496 下一个更大元素

本文发布于:2023-11-16 18:19:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630272.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更大   单调   训练营   元素   温度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!