zoukankan      html  css  js  c++  java
  • 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;
        }

  • 相关阅读:
    分分钟用上C#中的委托和事件
    AutoResetEvent详解
    C#跨线程调用
    多线程编程的注意事项
    C#中WinForm程序退出方法技巧总结
    用c#实现单链表(程序代码已经验证,完全正确)
    event & EventHandler
    Kubernetes理论02
    centos7 日志文件
    CentOS7 FTP安装与配置
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4747671.html
Copyright © 2011-2022 走看看