Created
March 5, 2013 23:29
-
-
Save daifu/5095350 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
| /* | |
| 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] | |
| */ | |
| /** | |
| * Definition for an interval. | |
| * public class Interval { | |
| * int start; | |
| * int end; | |
| * Interval() { start = 0; end = 0; } | |
| * Interval(int s, int e) { start = s; end = e; } | |
| * } | |
| */ | |
| import java.util.*; | |
| public class Solution { | |
| public ArrayList<Interval> merge(ArrayList<Interval> intervals) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if(intervals.size() == 0) return intervals; | |
| ArrayList<Interval> ret = new ArrayList<Interval>(); | |
| Collections.sort(intervals, INTERVAL_ORDER); | |
| Iterator<Interval> itr = intervals.iterator(); | |
| int start = intervals.get(0).start; | |
| int end = intervals.get(0).end; | |
| while(itr.hasNext()) { | |
| Interval tmp = itr.next(); | |
| if(end >= tmp.start) { | |
| end = Math.max(end, tmp.end); | |
| } else { | |
| ret.add(new Interval(start, end)); | |
| start = tmp.start; | |
| end = tmp.end; | |
| } | |
| } | |
| ret.add(new Interval(start, end)); | |
| return ret; | |
| } | |
| static final Comparator<Interval> INTERVAL_ORDER = new Comparator<Interval>() { | |
| public int compare(Interval i, Interval j) { | |
| return new Integer(i.start).compareTo(new Integer(j.start)); | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment