503-The Next Bigger Element II

table of Contents

Title description

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, and the first number after this number is larger than it, which means you should search for the next larger number cyclically. If it does not exist, -1 is output.

Example 1:
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 next largest number of the second 1 needs to be searched in a loop, and the result is also 2.

Source: LeetCode
Link: https://leetcode-cn.com/problems/next-greater-element-ii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

answer

  1. Refer to the official solution
  2. C language implementation
int* nextGreaterElements(int* nums, int numsSize, int* returnSize){
    
    
    *returnSize=numsSize;
    int* next=(int *)malloc(numsSize*sizeof(int));
    int* stack=(int *)malloc(numsSize*sizeof(int));//栈
    int top=-1;//栈指针

    for(int i=0;i<numsSize;i++)
    {
    
    
        while(top>-1&&nums[stack[top]]<nums[i])//当前元素比栈顶元素大则栈顶元素出栈
        {
    
    
            next[stack[top--]]=nums[i];
        }
        stack[++top]=i;//当前元素入栈
    }
    //循环查找
    for(int i=0;top>-1&&i<stack[top];i++)
    {
    
    
        while(top>-1&&nums[stack[top]]<nums[i])//当前元素比栈顶元素大则栈顶元素出栈
        {
    
    
            next[stack[top--]]=nums[i];
        }
    }
    //剩下无下一个更大元素
    while(top>-1)
    {
    
    
        next[stack[top--]]=-1;
    }
    free(stack);
    return next;
}
  1. General idea: Use the stack to store the subscript of the array, and compare the element corresponding to the subscript on the top of the stack with the current element. The size of the element corresponding to the subscript stored in the stack does not increase monotonically.

Guess you like

Origin blog.csdn.net/qq_36439722/article/details/112254065