@requires_authorization @create_time2015.7. Ten One: -@author Johnsondu@url https://leetcode.com/problems/merge-intervals//** * Array Sorting and then follow the greedy strategy to merge, specifically to see if the next element's start is between the current start and end, * If so, update the current end as needed. * Time Complexity (O (NLOGN))--Sort, results get O (n) * Spatial complexity (O (n )) *//** * Definition for an interval. * struct INTERVAL {* int start; * int end; * Interval (): Start (0), end (0) {} * Interval (int s, int e): Start (s), End (e) {} *}; */classSolution { Public:Static BOOLcmpConstInterval &a,ConstInterval &b) {if(A.start = = B.start)returnA.end < B.end;returnA.start < B.start; } vector<Interval>Merge vector<Interval>& intervals) {intLen = Intervals.size (); Sort (Intervals.begin (), Intervals.end (), CMP); vector<Interval>Ans for(inti =0; i < Len; i + +) {intst = Intervals[i].start;inted = intervals[i].end;intIDX = i +1; while(IDX < Len) {if(Intervals[idx].start >= St && intervals[idx].start <= ed) {if(Intervals[idx].end > ed) ed = Intervals[idx].end; IDX + +; }Else Break; } Interval tmp (ST, ed); Ans.push_back (TMP); i = idx-1; }returnAns }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode" 56. Merge intervals