Last active
April 7, 2016 03:45
-
-
Save cangoal/290435b5577787b8fed0 to your computer and use it in GitHub Desktop.
LeetCode - Insert Interval
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
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { | |
ArrayList<Interval> ret = new ArrayList<Interval>(); | |
if(intervals == null || intervals.size() == 0){ | |
ret.add(newInterval); | |
return ret; | |
} | |
for(int i=0; i<intervals.size(); i++){ | |
Interval curInterval = intervals.get(i); | |
if(curInterval.end < newInterval.start){ | |
ret.add(curInterval); | |
}else if(curInterval.start > newInterval.end){ | |
ret.add(newInterval); | |
newInterval = curInterval; | |
}else{ | |
newInterval.start = Math.min(newInterval.start, curInterval.start); | |
newInterval.end = Math.max(newInterval.end, curInterval.end); | |
} | |
} | |
ret.add(newInterval); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment