LeetCode [Sort]: Merge Intervals, leetcodemerge

Source: Internet
Author: User

LeetCode [Sort]: Merge Intervals, leetcodemerge

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

This question is actually not difficult. You only need to understand the various situations and use the insert sort method. My C ++ code implementation is as follows:

    vector<Interval> merge(vector<Interval> &intervals) {        vector<Interval> mergeIntervals;        for (auto interval : intervals) {            int i;            for (i = 0; i < mergeIntervals.size(); ++i) {                if (interval.end < mergeIntervals[i].start) {                    mergeIntervals.insert(mergeIntervals.begin() + i, interval);                    break;                }                else if (interval.start <= mergeIntervals[i].end) {                    mergeIntervals[i].start = min(interval.start, mergeIntervals[i].start);                    if (interval.end > mergeIntervals[i].end) {                        while (i + 1 < mergeIntervals.size() && interval.end >= mergeIntervals[i + 1].start) {                            mergeIntervals[i].end = mergeIntervals[i + 1].end;                            mergeIntervals.erase(mergeIntervals.begin() + i + 1);                        }                        mergeIntervals[i].end = max(interval.end, mergeIntervals[i].end);                    }                    break;                }            }            if (i == mergeIntervals.size())                mergeIntervals.push_back(interval);        }        return mergeIntervals;    }

Shows the time performance:


In addition, on Discuss, we see a solution (https://oj.leetcode.com/discuss/13953/a-simple-java-solution): First sort all input intervals by start using the sort function, and then insert them one by one. This method is also worth learning.

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.