<title>Leetcode Merge Intervals</title> Leetcode Merge Intervals
Ideas:
Take the left of the interval as the key value, sort the intervals, and then find the duplicates, and if you repeat, determine if you need to update the interval to add the current interval to the vector without repeating it.
/*** Definition for an interval.* struct Interval {* int start;* int end;* Interval (): Start (0), end (0) {}* Interval (int s, int e): Start (s), End (e) {} * }; */class Solution{ Public:Static BOOL CMP(Interval a,Interval b) {returnA.start < B.start; }Vector<Interval>Merge(Vector<Interval> &intervals) {int size= Intervals.size ();if(size = = 0 | | size = = 1)returnintervals; Sort (Intervals.begin (), Intervals.begin () +size, CMP);Vector<Interval>New_vec;int Start= Intervals[0].start;int End= Intervals[0].end; for(int I= 1; i < size; i++) {if(Intervals[i].start <= end) {// If you can merge if(End < Intervals[i].end) {// determine if you want to increase the rightend = Intervals[i].end; } }Else{New_vec.push_back (Interval (Start, end));// smaller than the left side of the interval, added directly to the collectionstart = Intervals[i].start; end = Intervals[i].end; }} new_vec.push_back (Interval (Start, end));// we've exited the loop at the last interval. returnNew_vec; }};
// createtime:2015-04-22 22:19:00#include <isotream>#include <cstdio>#include <algorithm>using namespace STD;typedef pair<int,int>Interval;BOOL CMP(Interval a,Interval b) {returnA.first < B.first;}int Main(void) {Vector<Interval>interval;// Interval.push_back (Make_pair (1, 4)); // Interval.push_back (Make_pair (1, 4));Interval.push_back (Make_pair (1, 3)); Interval.push_back (Make_pair (2, 6)); Interval.push_back (Make_pair (5, 7)); Interval.push_back (Make_pair (8, 10)); Interval.push_back (Make_pair (9, 12)); Interval.push_back (Make_pair (11, 18));int size= Interval.size (); Sort (Interval.begin (), Interval.begin () +size, CMP);Vector<Interval>New_vec;int Start= Interval[0].first;int End= Interval[0].second; for(int I= 1; i < size; i++) {if(Interval[i].first <= end) {if(End < Interval[i].second) {end = Interval[i].second; } }Else{New_vec.push_back (Interval (Start, end)); start = Interval[i].first; end = Interval[i].second; }} new_vec.push_back (Interval (Start, end));int size_2= New_vec.size (); for(int I= 0; i < size_2; i++) {printf ("%d%d\n", New_vec[i].first, New_vec[i].second); }return0;}
Leetcode Merge Intervals