Leetcode | | 57. Insert Interval

Source: Internet
Author: User

Problem:

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

Assume that the intervals were initially sorted according to their start times.

example 1:
Given Intervals [1,3],[6,9" , insert and Merge [2,5"  in as [1,5],[6,9] .

example 2:
Given  [1,2],[3,5],[6,7],[8,10],[12,16] , insert and Merge [4,9"  in as [1,2],[3,10],[12,16] .

This is because, the new interval [4,9] overlaps with [3,5],[6,7],[8,10] .

Hide TagsArray SortTest instructions: Similar to the 56 question, just to insert a new interval

Thinking:

If using Multimap<int, int> sorting, just insert newinterval into Multimap, specific reference 56 method

Code

Class solution {public:vector<interval> Insert (vector<interval> &intervals, Interval newinterval) {        vector<interval> ret;        Multimap<int,int> map_intervals;             if (Intervals.size () ==0)//boundary conditions a little change {ret.push_back (newinterval);        return ret; } for (Vector<interval>::iterator it=intervals.begin (); It!=intervals.end (); it++) Map_intervals.inse        RT (Make_pair (*it). Start, (*it). end)); Map_intervals.insert (Make_pair (newinterval.start,newinterval.end));//Add this line of code Multimap<int, Int>::iterator        P=map_intervals.begin ();        Interval tmp (P->first,p->second);                For (Multimap<int, Int>::iterator k=++p;k!=map_intervals.end (); k++) {if (k->first<=tmp.end)            Tmp.end=max (Tmp.end,k->second);                else {ret.push_back (TMP);                tmp.start=k->first;  tmp.end=k->second;          }} ret.push_back (TMP);            return ret; }};



Leetcode | | 57. Insert Interval

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.