[Merge intervals] Some tips

Source: Internet
Author: User

The leetcode contains several questions related to the merge of number intervals, which are roughly the place where there is an intersection, and these overlapping intervals are merged.

The idea is as follows:

First, sort all intervals according to the beginning, and then start traversing. Compare the size with the end of the currently determined interval and the header of the range to be judged,

1) if the tail is greater than or equal to the head, it indicates that there is an intersection. Then, let's see who has a bigger tail in the two ranges and take a bigger tail;

2) If the tail

Take leetcode56 as an example:

# Definition for an interval. # Class Interval (object): # def _ init _ (self, S = 0, E = 0): # self. start = s # self. end = eclass solution (object): def Merge (self, intervals): "": Type intervals: list [interval]: Rtype: list [interval] "If Len (intervals) = 0: return [] intervals = sorted (intervals, key = Lambda X: X. start) # sort by the first value of each small list incrementally. Res = [intervals [0] For N in intervals [1:]: If n. start <= res [-1]. end: res [-1]. end = max (N. end, Res [-1]. end) # The start of the second is smaller than the tail of the maximum range in res (found with-1) (to prove that the two have an intersection, and then take the greater tail of the two intersections) else: res. append (n) # If the small value of the second interval is greater than the tail of the maximum interval in res (it proves that there is no intersection) return res

  

[Merge intervals] Some tips

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.