C data structure and algorithm - find the first element on the right of each number in the array that is greater than it

Table of contents

Article Directory

topic

Find the first element on the right side of each number in the array that is greater than it, and output the subscript index, if not, mark -1.

Brute force method: nested loop comparison.

#include <stdio.h>
#include <stdlib.h>

// 查找数组中每个数右边第一个比它大的元素的下标索引
int *findNextGreaterElements(int *nums, int size) {
    
    
    int *result = (int *)malloc(size * sizeof(int));

    for (int i = 0; i < size; i++) {
    
    
        result[i] = -1; // 初始化结果为-1

        // 只比较当前数的右边
        for (int j = i + 1; j < size; j++) {
    
    
            if (nums[j] > nums[i]) {
    
    
                result[i] = j; // 找到右边第一个比当前元素大的元素,记录其下标索引
                break;
            }
        }
    }

    return result;
}

int main() {
    
    
    int nums[] = {
    
    3, 6, 8, 2, 5};
    int size = sizeof(nums) / sizeof(int);

    int *result = findNextGreaterElements(nums, size);

    printf("每个数右边第一个比它大的元素的下标索引:\n");
    for (int i = 0; i < size; i++) {
    
    
        printf("%d: %d\n", nums[i], result[i]);
    }

    free(result);

    return 0;
}

Guess you like

Origin blog.csdn.net/Jmilk/article/details/131061096