• 56.merge intervals


    56.merge intervals

    56.merge intervals
    Given a collection of intervals, merge all overlapping intervals.
    
    Example 1:
    
    Input: [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
    
    Example 2:
    
    Input: [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
    // 4ms
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <limits.h>
    
    //Definition for an interval.
    struct Interval {
        int start;
        int end;
    };
    
    int comp(const void *x, const void *y)
    {
        struct Interval a = *(struct Interval *)x;
        struct Interval b = *(struct Interval *)y;
        // ASC
        return a.start - b.start;
    }
    
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    struct Interval* merge(struct Interval* intervals, int intervalsSize, int* returnSize) {
        if(intervalsSize == 0) return intervals;
    
        struct Interval *result = (struct Interval *)malloc(sizeof(struct Interval) * intervalsSize);
        qsort(intervals, intervalsSize, sizeof(struct Interval), comp);
    
        *returnSize = 0;
        result[0].start = intervals[0].start;
        result[0].end = intervals[0].end;
        for (int i = 1; i < intervalsSize; ++i) {
            if(result[*returnSize].end < intervals[i].start)
            {
                ++*returnSize;
                result[*returnSize].start =  intervals[i].start;
                result[*returnSize].end =  intervals[i].end;
            }else if (result[*returnSize].end < intervals[i].end) {
                result[*returnSize].end =  intervals[i].end;
            }
            //(result[*returnSize].end >= intervals[i].end)
        }
        ++*returnSize;
        return result;
    }

    Connected Components

  • 相关阅读:
    对json按某个键的值进行排序(转载)
    nrm -- NPM registry 管理工具
    easyui-filebox 文件上传
    Netty,Thrifty
    VS2015 framework4.5代码提示英文切换为中文
    .NET Runtime version 2.0.50727.8762
    js moment.js日期操作类 datetime,日期操作,dayjs
    Oracle.ManagedDataAccess.dll
    打造自己的JavaScript武器库(转)
    Vue.js实战 5.5章 购物车
  • 原文地址:https://www.cnblogs.com/guxuanqing/p/9879879.html
Copyright © 2020-2023  润新知