Created
November 7, 2017 02:05
-
-
Save shailrshah/9f4035ba7d1ef4d2f2638af1764e76f2 to your computer and use it in GitHub Desktop.
Given a collection of intervals, merge all overlapping intervals.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // [1,3],[2,6],[8,10],[15,18] -> [1,6],[8,10],[15,18] | |
| public List<Interval> merge(List<Interval> intervals) { | |
| Collections.sort(intervals, (i1, i2) -> i1.start - i2.start); | |
| List<Interval> mergedIntervals = new ArrayList<>(); | |
| for(int i = 0; i < intervals.size(); i++) { | |
| int start = intervals.get(i).start; | |
| int end = intervals.get(i).end; | |
| while(i+1 < intervals.size() && intervals.get(i+1).start <= end) { | |
| end = Math.max(end, intervals.get(++i).end); | |
| } | |
| mergedIntervals.add(new Interval(start, end)); | |
| } | |
| return mergedIntervals; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment