Next Greater Element I

46 篇文章 0 订阅
2 篇文章 0 订阅

用遍历的办法,挨个比,效率比较低:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        
        int n=findNums.size();
        int m=nums.size();
        vector<int> flag;
        vector<int> re;
        vector<int> s;
        for(int i=0;i<n;i++)
        {
            flag.push_back(0);
            re.push_back(-2);
            s.push_back(findNums[i]);
        }
        
        
        for(int j=m-1;j>=0;j--)
        {
            for(int i=0;i<n;i++)
            {
                if(flag[i]==1)
                continue;          //continue和break啊......break是for就不循环了,continue是只跳过当前循环......
                if(nums[j]==findNums[i])
                {
                    flag[i]=1;
                    if(s[i]==findNums[i])
                    {
                        re[i]=-1;
                    }
                    else
                    {
                        re[i]=s[i];
                    }
                    
                }
                else
                {
                    if(nums[j]>findNums[i])
                    {
                        s[i]=nums[j];
                    }
                }
                
            }
        }
        return re;
        
    }
};



leetcode上答案的一种,先用栈做一个哈希表,做出来所有元素的next_greater的表,之后查表就好:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> s;
        unordered_map<int, int> m;
        for (int n : nums) {
            while (s.size() && s.top() < n) {
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        vector<int> ans;
        for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);    //由于是hash表,不会有重复,所以m.count(n)(数unordered_map<int,int>前面的int中有几个n)只会有0,1两种结果
        return ans;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值