Created
November 18, 2018 18:55
-
-
Save Abhishek-Chaudhary-InfoCepts/438a445063708de2229cb84a02aa05a2 to your computer and use it in GitHub Desktop.
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; } } | |
*/ | |
class MergeIntervals { | |
public List<Interval> merge(List<Interval> intervals) { | |
if (intervals.size() < 0) { | |
return null; | |
} | |
// meetings need not be sorted by time, do cleanup and sort by start time | |
Collections.sort(intervals, new Comparator<Interval>(){ | |
public int compare(Interval a, Interval b){ | |
return a.start - b.start; | |
} | |
}); | |
// iterate the loop only till last but one element as we are doing i+1 in logic | |
for (int i = 0; i < intervals.size() - 1; i++) { | |
if (intervals.get(i).end >= intervals.get(i + 1).start) { | |
intervals.get(i).end = getValidEnd(intervals, i); | |
intervals.remove(i+1); | |
//redo the processes once an interval is merged | |
// [[0,3],[1,2],[1,5]] -> [[0,5]] | |
i--; | |
} | |
} | |
return intervals; | |
} | |
public int getValidEnd(List<Interval> intervals, int i){ | |
return intervals.get(i).end < intervals.get(i + 1).end ? intervals.get(i + 1).end | |
: intervals.get(i).end; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment