LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Merge Intervals

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]. 

The requirement for this question is to merge a given set of intervals that overlap.

To merge an interval, first locate the adjacent interval and check whether there is overlap. If yes, merge the interval.

Therefore, first consider sorting the array. When sorting, you only need to sort by the start time of the interval. Then, the array is traversed. the end time of the Current interval is no less than the start time of the Current interval. This indicates that there are overlaps and needs to be merged. When merging, the end time of the new interval is equal to the maximum of the end time of the two intervals.

During implementation, the first interval is first placed in the new array, and then traversed from the second one. If there is overlap, the end time of the last element in the new array is changed; if there is no overlap, add it to the new array.

Time Complexity: O (nlogn)

Space complexity: O (n)

 1 bool cmp(Interval i1, Interval i2) 2 { 3     return i1.start < i2.start; 4 } 5  6 class Solution 7 { 8 public: 9     vector<Interval> merge(vector<Interval> &intervals)10     {11         vector<Interval> vi;12 13         if(intervals.size() == 0)14             return vi;15 16         sort(intervals.begin(), intervals.end(), cmp);17 18         vi.push_back(intervals[0]);19         for(int i = 1; i < intervals.size(); ++ i)20         {21             if(vi[vi.size() - 1].end >= intervals[i].start)22                 vi[vi.size() - 1].end = max(vi[vi.size() - 1].end, intervals[i].end);23             else24                 vi.push_back(intervals[i]);25         }26         return vi;27     }28 };

Reprinted please note the Source: LeetCode --- 56. Merge Intervals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.