Check in (10)

https://leetcode-cn.com/problems/next-greater-element-ii/
I wrote it myself is really too slow, the speed is only over 5%, ==
But it is all written by myself, so I feel more fulfilled .

There are a lot of pruning places, probably. When you have determined that the larger element of the previous element is in a certain position, then the range of the larger element of the element you are looking for can be narrowed according to the quantitative relationship. I feel that my code may have some redundant operations. , So it's very slow.
But my space complexity is really small. (Satisfied! It's
all written in the code.

class Solution {
    
    
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
    
    
        int des=1;//标记要比较的跨越步长
        int n=nums.size();//元素的个数
        vector<int> res(n,-1);//返回答案的容器
        int max=n;//des的自加上限
        for(int i=0;i<n;){
    
    //从0开始逐步比较
            if(nums[(des+i)%n]>nums[i]||des==max){
    
    //当找到一个更大的值的时候,或者当已经无路可走的时候
                res[i]=nums[(des+i)%n];//答案都可以确定为
                if(res[i]==nums[i]) res[i]=-1;
                i++;
                while(i<n&&nums[i-1]==nums[i]){
    
    
                    //用于简化相等时候的一切都可连等下去
                    res[i]=res[i-1];
                    des--;
                    i++;
                }
                if(i==n) break;//当确定了所有的值时候
                if(nums[i]>nums[i-1]) max=n;//
                else max=des-1;//否则若是小于它,则不会超过上一个的步长减去一个1
                des=1;//步长初始化
            }
            else if(max>des) des++;
        }
        return res;
    }
};

In fact, using a monotonic stack can be faster as follows:

class Solution {
    
    
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
    
    
        int n = nums.size();
        vector<int> ret(n, -1);
        stack<int> stk;
        for (int i = 0; i < n * 2 - 1; i++) {
    
    
            while (!stk.empty() && nums[stk.top()] < nums[i % n]) {
    
    
                ret[stk.top()] = nums[i % n];
                stk.pop();
            }
            stk.push(i % n);
        }
        return ret;
    }
};

Author: LeetCode-Solution
link: https: //leetcode-cn.com/problems/next-greater-element-ii/solution/xia-yi-ge-geng-da-yuan-su-ii-by-leetcode-bwam /
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_47741017/article/details/114435817