Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active April 7, 2016 03:45
Show Gist options
  • Save cangoal/290435b5577787b8fed0 to your computer and use it in GitHub Desktop.
Save cangoal/290435b5577787b8fed0 to your computer and use it in GitHub Desktop.
LeetCode - Insert Interval
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