[Leetcode] merge intervals

Source: Internet
Author: User
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].

 

Algorithm ideas:

Sort intervals by START, create an empty list, insert the intervals elements one by one, and merge them.

It is worth noting that if the element to be inserted in intervals can be merged with the element in the list, it must be merged with the last one. Think about it

[Tucao]: This is the algorithm that came up with the first time. It is still very good. It is a single traversal, but it will not be sorted manually by collections. Sort () at that time. O (Clerk □clerk) O

 1 /** 2  * Definition for an interval. 3  * public class Interval { 4  *     int start; 5  *     int end; 6  *     Interval() { start = 0; end = 0; } 7  *     Interval(int s, int e) { start = s; end = e; } 8  * } 9  */10 public class Solution {11     List<Interval> res = new ArrayList<Interval>();12     public List<Interval> merge(List<Interval> intervals) {13         if(intervals == null || intervals.size() == 0) return res;14         Collections.sort(intervals, new Comparator<Interval>(){15             public int compare(Interval a,Interval b){16                 return a.start - b.start;17             }18         });19         List<Interval> list = new ArrayList<Interval>();20         list.add(intervals.get(0));21         for(int i = 1; i < intervals.size(); i++){22             Interval last = list.get(list.size() - 1);23             Interval thus = intervals.get(i);24             if(thus.start <= last.end){25                 last.end = thus.end > last.end ? thus.end : last.end;26             }else{27                 list.add(thus);28             }29         }30         return list;31     }32 }

 

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.