[LeetCode] 56. Merge Intervals, leetcode56.merge
[Question]
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].
[Analysis]
(1) first sort the array of the target range in ascending order of the X axis. Example: [2, 3] [1, 2] [3, 9]-> [1, 2] [2, 3] [3, 9]
(2) scan the sorted array of target intervals and combine these intervals into several different intervals. For example, [2, 3] [1, 2] []-> [1, 3] []
There are three situations:
A: [] []-> [] the end of the first interval is greater than or equal to the start of the second interval, and the end of the second interval is greater than the end of the first interval
B: [] []-> [] the end of the first interval is greater than or equal to the start of the second interval, and the end of the second interval is smaller than the end of the first interval
C: [1, 2] [3, 4]-> [1, 2] [3, 4] The end of the first interval is smaller than the start of the second interval
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 56. merge Intervals * URL: https://oj.leetcode.com/problems/merge-intervals/* result: AC * Source: LeetCode * blog: * *********************************/# include <iostream> # include <algorithm> # include <vector> using namespace std; struct Interval {int start; int end; Interval (): start (0), end (0) {} Interval (int s, int e): start (s ), end (e) {}}; class Solution {public: // comparison function static bool cmp (const Interval & ina, const Interval & inb) {return ina. start <inb. start;} vector <Interval> merge (vector <Interval> & intervals) {vector <Interval> result; int count = intervals. size (); if (count <= 1) {return intervals;} // if // X axis sort (intervals. begin (), intervals. end (), cmp); // merge result. push_back (intervals [0]); // consider three cases for (int I = 1; I <count; I ++) {Interval preIn = result. back (); Interval curIn = intervals [I]; // [1, 3] [2, 6] if (curIn. start <= preIn. end & curIn. end> preIn. end) {preIn. end = curIn. end; result. pop_back (); result. push_back (preIn);} // if // [1, 2] [3, 4] else if (curIn. start> preIn. end) {result. push_back (curIn);} // [] [2, 3] Do not do anything} // for return result ;}}; int main () {Solution; interval in1 (); Interval in2 (); Interval in3 (); Interval in4 (); vector <Interval> vec; vec. push_back (in1); vec. push_back (in2); vec. push_back (in3); vec. push_back (in4); // merge vector <Interval> v = solution. merge (vec); // output for (int I = 0; I <v. size (); I ++) {Interval in = v [I]; cout <"[" <in. start <"," <in. end <"]" <endl;} // for return 0 ;}