[LeetCode]496. Next Greater Element I

[LeetCode]496. Next Greater Element I

题目描述

这里写图片描述

思路

对每个数,遍历找到在目标数组中的位子,然后在位子之后找比他大的数,找到即寻找下一个数
update
使用栈和map
对于在nums中出现的每个数,在map中保存<这个数,该位置之后的第一个比他大的数>,然后再遍历findNums,用map确定每一位对应的值,不存在的对应-1

代码

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        vector<int> result;
        for (int i = 0;  i < findNums.size(); ++i){
            int finded = -1, flag = -1;

            for (int j = 0; j < nums.size(); ++j) {
                if (flag != -1 && nums[j] > nums[flag]) {
                    finded = nums[j];
                    break;
                }
                if (findNums[i] == nums[j]){
                    flag = j;
                }

            }
            result.push_back(finded);
        }

        return result;

    }
};

update

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        vector<int> result;
        stack<int> compare;
        unordered_map<int, int> finded;

        for (auto &p : nums){
            while (compare.size() && compare.top() < p){
                finded[compare.top()] = p;
                compare.pop();
            }
            compare.push(p);
        }
        for (auto &p : findNums){
            result.push_back(finded.count(p) ? finded[p] : -1);
        }

        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值