代码随想录算法训练营第五十八天 |739. 每日温度、496. 下一个更大元素 I

69 阅读1分钟

代码随想录算法训练营第五十八天 |739. 每日温度、496. 下一个更大元素 I

单调栈:

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

739. 每日温度

题目链接:739. 每日温度

  • 3种情况讨论,比栈顶大,比栈顶小或者等于
  •  class Solution {
     public:
         vector<int> dailyTemperatures(vector<int>& temperatures) {
             int n = temperatures.size();
             vector<int> res(n);
             // 这里放元素索引,而不是元素
             stack<int> s; 
             /* 单调栈模板 */
             for (int i = n - 1; i >= 0; i--) {
                 while (!s.empty() && temperatures[s.top()] <= temperatures[i]) {
                     s.pop();
                 }
                 // 得到索引间距
                 res[i] = s.empty() ? 0 : (s.top() - i); 
                 // 将索引入栈,而不是元素
                 s.push(i); 
             }
             return res;
         }
     };
    

496. 下一个更大元素 I

题目链接:496. 下一个更大元素 I

  • 递增栈是从栈头到栈底递增
  • 这里需要2中元素在1中的映射
  •  class Solution {
     public:
         vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
             int len1 = nums1.size();
             int len2 = nums2.size();
             vector<int> res(len1, -1);
             stack<int> st;
     ​
             unordered_map<int, int> umap;
             for (int i = 0; i < len1; i++) {
                 // 映射 nums[i]到i,便于之后使用
                 umap[nums1[i]] = i;
             }
     ​
             st.push(nums2[0]);
             for (int i = 1; i < len2; i++) {
                 while (!st.empty() && st.top() < nums2[i]) {
                     if (umap.count(st.top())) {
                         res[umap[st.top()]] = nums2[i];
                     }
                     st.pop();
                 }
                 st.push(nums2[i]);
             }
             return res;
         }
     };