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 }