Created
December 21, 2016 20:06
-
-
Save jianminchen/a75a3ff78dbb863774b3b97da0d150f8 to your computer and use it in GitHub Desktop.
Leetcode - Merge Intervals - http://xiaoyaoworm.com/blog/2016/06/27/%E6%96%B0leetcode56-merge-intervals/
This file contains 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 List<Interval> merge(List<Interval> intervals) { | |
List<Interval> result = new ArrayList<Interval>(); | |
if(intervals == null || intervals.size() == 0) return result; | |
Comparator<Interval> comparator = new Comparator<Interval>(){ | |
public int compare(Interval p, Interval q){ | |
return p.start - q.start; | |
} | |
}; | |
Collections.sort(intervals, comparator); | |
Interval base = intervals.get(0); | |
for(int i = 1; i < intervals.size(); i++){ | |
Interval current = intervals.get(i); | |
if(base.end < current.start){ | |
result.add(base); | |
base = current; | |
} | |
base = new Interval(base.start, Math.max(base.end, current.end)); | |
} | |
result.add(base); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment