leetcode-496-Next Greater Element I

问题

题目:[leetcode-496]

思路

简单题,仔细一点。

代码

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int sz1 = findNums.size();
        int sz2 = nums.size();
        std::vector<int> ret(sz1, int());
        for(int i = 0; i < sz1; ++i){
            int j = 0;
            for(j = 0;j < sz2; ++j){
                if( nums[j] == findNums[i] )
                    break;
            }
            if(j==sz2)
                ret[i] = -1;
            else{
                int k = 0;
                for(k = j + 1; k < sz2; ++k){
                    if(nums[k] > nums[j]){
                        ret[i] = nums[k];
                        break;
                    }
                }
                if(k==sz2) ret[i] = -1;
            }
        }
        return ret;
    }
};

思路1

当然,这题有O(N)复杂度的解法。
参考这个链接[Next Greater Element]。当然这个题目本生的意思和题面有一点不同。该题是求数组中任意一个元素的下一个较大元素。
算法如下:

Method 2 (Using Stack)
Thanks to pchild for suggesting following approach.
1) Push the first element to stack.
2) Pick rest of the elements one by one and follow following steps in loop.
….a) Mark the current element as next.
….b) If stack is not empty, then pop an element from stack and compare it with next.
….c) If next is greater than the popped element, then next is the next greater element for the popped element.
….d) Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements
….g) If next is smaller than the popped element, then push the popped element back.
3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.

简言之,挨个判断数组元素。如果栈顶比当前元素小,那么栈顶的nextGreater元素就是当前元素。继续判断栈顶和当前元素的关系,知道栈顶比当前元素大或者是栈空,将当前元素入栈即可。
挨个判断结束之后,栈中剩余元素的nextGreater元素均是-1

代码1

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int sz1 = findNums.size();
        int sz2 = nums.size();
        std::vector<int> ret(sz1, int());
        if(!sz1 || !sz2) return ret;

        std::map<int, int> mapper;
        std::stack<int> stk;

        stk.push(nums[0]);
        for(int i = 1; i < sz2; ++i){

            while(!stk.empty() && stk.top() < nums[i] ){
                mapper[stk.top()] = nums[i];
                stk.pop();
            }
            stk.push(nums[i]);
        }
        while(!stk.empty()){
            mapper[stk.top()] = -1;
            stk.pop();
        }

        for(int i = 0; i < sz1; ++i){
            ret[i] = mapper[findNums[i]];
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值