Java examples for Algorithm:Array
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].
Make sure the returned intervals are sorted.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { List<Interval> intervals; intervals = new ArrayList<>(); intervals.add(new Interval(1, 3)); intervals.add(new Interval(2, 5)); intervals.add(new Interval(1, 10)); printRslt(new Solution().merge(intervals)); intervals = new ArrayList<>(); intervals.add(new Interval(1, 3)); intervals.add(new Interval(2, 6)); intervals.add(new Interval(8, 10)); intervals.add(new Interval(15, 18)); printRslt(new Solution().merge(intervals)); }//from www. j a v a 2 s .co m private static void printRslt(List<Interval> intervals) { for (Interval interval : intervals) { System.out.print("[" + interval.start + ", " + interval.end + "], "); } System.out.println(); } } class Solution { public List<Interval> merge(List<Interval> intervals) { List<Interval> rslt = new ArrayList<>(); Collections.sort(intervals, (Interval o1, Interval o2) -> { return Integer.signum(o1.start - o2.start) != 0 ? Integer.signum(o1.start - o2.start) : Integer.signum(o1.end - o2.end); }); for (int i = 0; i < intervals.size(); ++i) { Interval mergeInterval = intervals.get(i); ++i; while (i < intervals.size() && overlap(mergeInterval, intervals.get(i))) { mergeInterval.start = Math.min(mergeInterval.start, intervals.get(i).start); mergeInterval.end = Math.max(mergeInterval.end, intervals.get(i).end); ++i; } --i; rslt.add(mergeInterval); } return rslt; } private boolean overlap(Interval o1, Interval o2) { return !(Math.max(o1.start, o2.start) > Math.min(o1.end, o2.end)); } } class Interval { int start; int end; Interval() { start = end = 0; } Interval(int s, int e) { start = s; end = e; } }