leetcode-496-Next Greater Element I

来源:互联网 发布:php病毒get参数 编辑:程序博客网 时间:2024/05/22 10:43

问题

题目:[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;    }};
0 0
原创粉丝点击