自学内容网 自学内容网

C语言 | Leetcode C语言题解之第436题寻找右区间

题目:

题解:

typedef struct {
    int start;
    int index;
} Node;

int cmp(const void *pa, const void *pb) {
    return ((Node *)pa)->start - ((Node *)pb)->start;
}

int* findRightInterval(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize){
    Node * startIntervals = (Node *)malloc(sizeof(Node) * intervalsSize);
    Node * endIntervals = (Node *)malloc(sizeof(Node) * intervalsSize);
    for (int i = 0; i < intervalsSize; i++) {
        startIntervals[i].start = intervals[i][0];
        startIntervals[i].index = i;
        endIntervals[i].start = intervals[i][1];
        endIntervals[i].index = i;
    }
    qsort(startIntervals, intervalsSize, sizeof(Node), cmp);
    qsort(endIntervals, intervalsSize, sizeof(Node), cmp);

    int * ans = (int *)malloc(sizeof(int) * intervalsSize);
    for (int i = 0, j = 0; i < intervalsSize; i++) {
        while (j < intervalsSize && endIntervals[i].start > startIntervals[j].start) {
            j++;
        }
        if (j < intervalsSize) {
            ans[endIntervals[i].index] = startIntervals[j].index;
        } else {
            ans[endIntervals[i].index] = -1;
        }
    }
    *returnSize = intervalsSize;
    free(startIntervals);
    free(endIntervals);
    return ans;
}

原文地址:https://blog.csdn.net/m0_59237910/article/details/142537126

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!