Question | Answer |
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]. | private class IntervalComparator implements Comparator<Interval> { @Override public int compare(Interval a, Interval b) { return a.start < b.start ? -1 : a.start == b.start ? 0 : 1; } } public List<Interval> merge(List<Interval> intervals) { Collections.sort(intervals, new IntervalComparator()); LinkedList<Interval> mergedList = new LinkedList<Interval>(); for(Interval interval : intervals){ if(mergedList.isEmpty() || mergedList.getLast().end < interval.start ){ mergedList.add(interval); }else{ mergedList.getLast().end = Math.max( mergedList.getLast().end , interval.end); } } return mergedList; } |
There are no comments, be the first and leave one below:
Want to create your own Flashcards for free with GoConqr? Learn more.