• Merge Intervals


    Description:

    Given a collection of intervals, merge all overlapping intervals.

    For example,
    Given [1,3],[2,6],[8,10],[15,18],
    return [1,6],[8,10],[15,18].

    Code:

       int partition(vector<Interval>& intervals, int low, int high)
        {
            Interval key(intervals[low].start, intervals[low].end);
            while (low<high){
                while (low < high && intervals[high].start>=key.start)--high;
                intervals[low].start = intervals[high].start;
                intervals[low].end = intervals[high].end;
                
                while (low < high && intervals[low].start<=key.start)++low;
                intervals[high].start = intervals[low].start;
                intervals[high].end = intervals[low].end;
            }
                intervals[low].start = key.start;
                intervals[low].end = key.end;
                return low;
        }
        void quickSort(vector<Interval>& intervals, int low, int high)
        {
            if (low < high)
            {
                int pos = partition(intervals,low,high);
                quickSort(intervals, low, pos);
                quickSort(intervals, pos+1,high);
            }
        }
        void quickSort(vector<Interval>& intervals){
            quickSort(intervals,0,intervals.size()-1);
        }
        vector<Interval> merge(vector<Interval>& intervals) {
            vector<Interval>result;
            quickSort(intervals);
            unsigned int n = intervals.size();
            if (n==0)
                return result;
            result.push_back(intervals[0]);
            for (int i = 1; i < n; ++i)
            {
                int temp = result.size();
                if (intervals[i].start <= result[temp-1].end)
                    result[temp-1].end = max(intervals[i].end,result[temp-1].end);
                else
                    result.push_back(intervals[i]);
            }
            return result;
        }

  • 相关阅读:
    安装centos出现的问题
    linux学习笔记
    sails框架结合mocha的测试环境搭建
    sails框架结合mocha
    使用postman发送http请求
    C++之易混淆知识点三---算法分析
    复习一下单链表的常用操作
    C++之易混淆知识点二
    FPGA之阻塞赋值与非阻塞赋值
    C++之易混淆知识点一-----static详解
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4747671.html
Copyright © 2020-2023  润新知