Skip to content

Instantly share code, notes, and snippets.

@maydayco
Created June 5, 2013 21:54
Show Gist options
  • Save maydayco/5717634 to your computer and use it in GitHub Desktop.
Save maydayco/5717634 to your computer and use it in GitHub Desktop.
Insert Interval
/**
* 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> insert(ArrayList<Interval> intervals, Interval newInterval) {
// Start typing your Java solution below
// DO NOT write main() function
Interval pre = new Interval();
ArrayList<Interval> res = new ArrayList<Interval>();
boolean inserted = false;
for (Interval cur : intervals) {
if (cur.end < newInterval.start) {
res.add(cur);
continue;
}
if (!inserted && cur.start > newInterval.end) {
pre = newInterval;
inserted = true;
res.add(newInterval);
res.add(cur);
} else if (inserted) {
if (cur.start <= pre.end)
pre.end = Math.max(cur.end, pre.end);
else {
res.add(cur);
pre = cur;
}
} else {
pre.start = Math.min(cur.start, newInterval.start);
pre.end = Math.max(cur.end, newInterval.end);
res.add(pre);
inserted = true;
}
}
if (!inserted)
res.add(newInterval);
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment