leetcode 503. Next Greater Element II

题意:

给定一个环形数组 nums, 对于每个元素e,找出e右边出现的第一个e',满足e‘ > e,若不存在e‘,令e’ 等于 1;

Example:

给定 nums = {1, 2, 1},返回 {2,-1, 2} 

思路:

1.  右向左利用栈保持一个升序数组 sta,若第 i 个元素与 sta 的头元素相比:

   a. nums[i] >= sta.top(), sta循环弹出头元素,直到sta为空或 nums[i] < sta.top()。

   b. nums[i] < sta.top(), 则显然 sta.top() 就是 e’, nums[i] 就是 e。 

此时将nums[i] 入栈,保持sta为一个升序数组。

2.   显然第一步只能找到部分 e', 如 {1,2,1} 从右到左遍历时,第二个 '1' 此时不能找到 e'

      注意到两点: 

           a. sta此时是一个升序数组

           b.nums中此时未找到e’的元素组成一个非升序数组nums'

3. 继续从右向左遍历 nums', 在 sta 中找到 e'


代码:

时间复杂度 O(n), 空间复杂度 O (n)

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> ret (nums.size(), -1);
        vector<bool> isFound(nums.size(), false);
        stack<int> sta;
        for (int i = nums.size() - 1; i >= 0; --i){
            while (!sta.empty() && sta.top() <= nums[i])
                sta.pop();
            if (!sta.empty()){
                ret[i] = sta.top();
                isFound[i] = true;
            }
            sta.push(nums[i]);
        }
        for (int i = nums.size() - 1; i >= 0; --i){
            if (isFound[i] == false){
                while (!sta.empty() && sta.top() <= nums[i])
                    sta.pop();
                if (!sta.empty())
                    ret[i] = sta.top();
            }
        }
        return ret;
    }
};




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值