Topic link Merge Intervals
/** * Definition for an interval. * public class Interval {* int start; * int end; * Interval () {start = 0; end = 0;} * Interval (int s, I NT e) {start = s; end = e;} * Title: Leetcode The 56th merge intervals interval merges the set of the given interval, merging the overlapping parts of the adjacent intervals * idea: Now the set of this interval is sorted from large to small, After traversing if the end of the current collection is greater than the head of the next set, then there is a coincidence to merge, and continue to judge the size of the interval after merging with the next interval of the head of the relationship, and then into the interval of the answer, if the tail is greater than less than the next interval of the head is not coincident, the current interval is public class Solution {public list<interval> merge (list<interval> intervals) {if (Intervals.size () = = 0 | | Intervals.size () = = 1) return intervals; List<interval> answer = new arraylist<interval> ();//Note: The List is a virtual class that cannot be initialized directly, it is initialized with its subclasses, that is, if it is new list< Interval> error Collections.sort (intervals,new intervalcomparator ());//First set the input interval set Interval pre = Intervals.get (0); for (int i = 1;i < Intervals.size (); i++) {Interval Curr = Intervals.get (i); if (Pre.end < Curr.start) {//interval without merging Answer.add (PRE); pre = Curr; } else{Interval merge = new Interval (pre.start,pre.end>curr.end?pre.end:curr.end); Pre = merge; }} answer.add (pre); return answer; }}class Intervalcomparator implements Comparator<interval>{public int compare (Interval A,interval b) {return A.start-b.start;}}
"Leetcode" Merge intervals to sort by comparator