Lintcode-easy-insert Interval

Source: Internet
Author: User

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list was still in order and non-overlapping (merge intervals if neces Sary).

Example

Insert [2, 5] into [[up], [5,9]], we get [[1,9]].

Insert [3, 4] into [[up], [5,9]], we get [[up], [3,4], [5,9]].

This problem remember the first time when the brush took a long time to do out, read the next nine chapters on the algorithm affixed to the answer, I think the answer is written well, as follows

/*** Definition of Interval: * Public classs Interval {* int start, END; * Interval (int start, int end) {* This.start = start; * This.end = end; *     } */classSolution {/*** Insert newinterval into intervals. * @paramintervals:sorted interval list. * @paramnewinterval:a new interval. * @return: A new sorted interval list. */     Publicarraylist<interval> Insert (arraylist<interval>intervals, Interval newinterval) {ArrayList<Interval> result =NewArraylist<interval>(); //Write your code here                if(Intervals = =NULL|| NewInterval = =NULL)            return NULL; intinsertposition = 0;  for(Interval interval:intervals) {if(Newinterval.start >interval.end)                {Result.add (interval); Insertposition++; }            Else if(Newinterval.end <Interval.start)            {Result.add (interval); }            Else{Newinterval.start=math.min (Newinterval.start, Interval.start); Newinterval.end=Math.max (Newinterval.end, interval.end);                }} result.add (Insertposition, newinterval); returnresult; }}

Lintcode-easy-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.