[503] C language LeetCode brush. The next greater element II (M)

Given a loop array (the last element of the next element is the first element of the array), the output of each element of the next higher element. The next element of a larger number x is based on an array traversal order, bigger than its first number after this number, which means that you should search for its next cycle of a larger number. If not, then the output of -1.

Example 1:

Input: [1,2,1]
Output: [2, 1,2]
Explanation: a first next higher number is 1 2;
a larger number can not be found under the numbers 2; 
second the next largest number of cycles required 1 search result is 2.
Note: The length of the input array does not exceed 10000.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/next-greater-element-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Three cycles, an enumeration, a looking element behind, to find a previous element.

int* nextGreaterElements(int* nums, int numsSize, int* returnSize){
    int i, j, k;
    int *out;
    int flag = 0;
    
    out = (int *)malloc(sizeof(int) * numsSize);
    
    for (i = 0; i < numsSize; i++) {
        flag = 0;
        for(j = i+1; j < numsSize; j++) {
            if (nums[j] > nums[i]) {
                out[i] = nums[j];
                flag = 1;
                break;
            }
            
        }
            
        if(flag == 0) {
            for(k=0; k < i; k++) {
                if(nums[k] > nums[i]) {
                    out[i] = nums[k];
                    flag = 1;
                    break;
                }
            }
            
            if (flag == 0) {out[i] = -1;}
        }
    }
    
    *returnSize = numsSize;
    
    return out;
}

 

Published 149 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/jin615567975/article/details/104416823