[Leetcode] 503. Next-greater-element-ii (stack) [medium]

link

https://leetcode-cn.com/problems/next-greater-element-ii/

time consuming

Problem solving: 15 min
Problem solving: 9 min

Title

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 traversal order of the array. 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.

Note: The length of the input array will not exceed 10000.

Ideas

It is the first time to traverse each element in the array and put it on the stack. Before pushing it on the stack, judge that if the current element is greater than the top element on the stack, then the current element is the next larger number of the top element on the stack, and the result array The position corresponding to the top element of the middle stack becomes the current element, and the top element of the stack is popped until the top element of the stack is no longer larger than the current element, and the current element is pushed onto the stack.

Because it is a looping array, each element in the array needs to be traversed a second time, this time it is no longer on the stack, and the rest is the same as the first time.

Each element is pushed and popped once.

Time complexity: O (n) O(n)O ( n )

AC code

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

Guess you like

Origin blog.csdn.net/Krone_/article/details/114434983