Last active
December 14, 2015 07:49
-
-
Save guolinaileen/5052977 to your computer and use it in GitHub Desktop.
learn how to create a comparator
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
/** | |
* 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; } | |
* } | |
*/ | |
public class Solution { | |
public ArrayList<Interval> merge(ArrayList<Interval> intervals) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
ArrayList<Interval> result=new ArrayList<Interval>(); | |
if(intervals.size()==0) return result; | |
Comparator<Interval> INTERVAL_ORDER=new Comparator<Interval>() | |
{ | |
@Override | |
public int compare(Interval i, Interval j) | |
{ | |
return new Integer(i.start).compareTo(new Integer(j.start)); | |
} | |
}; | |
Collections.sort(intervals, INTERVAL_ORDER); | |
int s=intervals.get(0).start; | |
int e=intervals.get(0).end; | |
result.add(intervals.get(0)); | |
for(int i=1; i<intervals.size(); i++) | |
{ | |
if(intervals.get(i).start>=s && intervals.get(i).start<=e) | |
{ | |
result.remove(result.size()-1); | |
e=Math.max(e, intervals.get(i).end); | |
}else | |
{ | |
s=intervals.get(i).start; e=intervals.get(i).end; | |
} | |
result.add(new Interval(s, e)); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment