[Monotone stack] [leetcode] [medium] 503. The next bigger element II

topic:

Given a looping array (the next element of the last element is the first element of the array), output the next larger element of each element. The next larger element of the number x is in the array traversal order. The first number after this number is larger than it, which means you should search for the next larger number in a loop. If it does not exist, -1 is output.

Example:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The next greater number of the first 1 is 2; the
number 2 cannot find the next greater number; the
second The next largest number of 1 requires a loop search, and the result is also 2.

Original title address:

503. The Next Greater Element II

Problem-solving ideas: monotonic stack

Monotonic stack, similar to monotonic queue, is an increasing or decreasing stack, that is, the data returned by calling pop() is increasing or decreasing.

Since it is a stack, there are 3 basic operations:

  • push(x): Push x into the stack. In order to ensure that the data in the stack is in order, compare the top element and the size of x from the top of the stack, until the position of x is found, and some data is deleted by pop during this process.
  • pop(): delete the top element of the stack
  • top(): the top element of the stack

For this question, how to use the monotonic stack, first look at the example, if the array: [4, 3, 2, 5, 5, 2, 1], it should return [5, 5, 5, -1, -1, 4, 4] .

Push(4) pushes 1, 2 out of the stack, so the next maximum value of 1, 2 is 4.

To start from the beginning, you only need to push the maximum value once into the stack, but the code is complicated, and it can be completely traversed in 2 passes.

c++ code:

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> ret(nums.size(), -1);
        if (nums.empty()) return ret;

        stack< pair<int, int> > s; // 记录当前数字及其位置
        for (int j = 0; j < 2; j++) {
            for (int i = 0; i < nums.size(); i++) {
                while (!s.empty()) {
                    pair<int, int> p = s.top();
                    if (p.first < nums[i]) {
                        ret[p.second] = nums[i]; // 根据位置更改ret数组
                        s.pop();
                    } else {
                        break;
                    }
                }
                s.push(make_pair(nums[i], i));
            }
        }

        return ret;
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/114457502