leetcode 496下一个更大的元素I

单调递减栈来做,time O(n),spaceO(n)需要一个哈希map

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        //用一个从栈底到栈顶单调递减的栈来做这个题,从右往左遍历;
        //1. 如果栈顶元素大于当前元素,说明右边第一个比x大的元素为栈顶;
        //2. 如果栈顶元素小于当前元素,则把栈顶元素pop掉,然后重复上一行制导栈为空;
        //   因为就算以后的元素要找next greater至少也会是当前元素,因为当前元素离
        //   以后的元素更近,而且值更大;
        int len1=nums1.size();
        if(len1==0) return {};
        stack<int> s;
        unordered_map<int,int> m;//map<num2,nextgreater>
        vector<int> res;
        for(int i=nums2.size()-1;i>=0;i--){
            
            while(!s.empty()){
                if(s.top()>nums2[i]){
                    m[nums2[i]]=s.top();break;
                }else{
                    s.pop();
                }
            }
            if(s.empty()){
                m[nums2[i]]=-1;
            }
            s.push(nums2[i]);  
        }
        
        for(int i=0;i<len1;i++){
            res.push_back(m[nums1[i]]);
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10972357.html
今日推荐