503. Next Greater Element II

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

Example 1:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number; 
The second 1's next greater number needs to search circularly, which is also 2.

Note: The length of given array won't exceed 10000.

题意:给出一个循环数组,找出每个元素的下一个大于它的值,若不存在,则记为-1。

方法一:观测到数据范围并不大,暴力破解:

class Solution{
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        int len=nums.size();
        for(int i=0; i<len; i++) {
            nums.push_back(nums[i]);
        }
        vector<int>vec(len,-1);
        for(int i=0; i<len; i++) {
            for(int j=i+1; j<i+len; j++){
                if(nums[j]>nums[i]) {
                    vec[i]=nums[j];
                    break;
                }
            }
        }
        return vec;
     }
};

方法二:维护一个栈,栈中的元素都未找到下一个大于它的值。当栈为空或者当前栈顶元素大于遍历到的nums[i]时,nums[i]进栈,表示nums[i]还未找到下一个大于它的值。当栈顶元素小于nums[i]时,则有栈顶元素找到下一个较大的元素,将其出栈并记录。nums数组为循环数组,可以将其复制一遍,再加入数组。

class Solution{
public:
    vector<int> nextGreaterElements(vector<int>& nums){
        stack<int>st;
        int len=nums.size();
        vector<int>vec(len,-1);
        for(int i=0; i<len*2; i++) {
            int j=i%len;
            while(!st.empty()&&nums[st.top()]<nums[j]) { 
            //栈顶元素找到下一个大于它的值
                vec[st.top()]=nums[j];
                st.pop();
            }
            if(i<len)    //当前元素入栈
                st.push(i);
        }
        return vec;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值