Back to course home
0% completed
Vote For New Content
Can't we do this in O(N) time complexity without sorting like so?
Satya Pandya
Jul 25, 2023
public List<Interval> merge(List<Interval> intervals) { List<Interval> mergedIntervals = new LinkedList<Interval>(); // TODO: Write your code here if(intervals.size()<2) return intervals; Interval l; Interval r; mergedIntervals.add(0, intervals.get(0)); intervals.remove(0); int ls; int le; Iterator<Interval> intervalItr = intervals.iterator(); while (intervalItr.hasNext()) { l=mergedIntervals.get(0); r=intervalItr.next(); if(overlap(l, r)){ ls = l.start; le = l.end; mergedIntervals.remove(0); mergedIntervals.add(0, new Interval(Math.min(ls, r.start), Math.max(le, r.end))); } else mergedIntervals.add(new Interval(r.start, r.end)); } return mergedIntervals; } public boolean overlap(Interval l, Interval r) { if(l.start >= r.start && l.start <= r.end){ return true; } else if(l.end >= r.start && l.end <= r.end){ return true; } else if(r.start >= l.start && r.start <= l.end){ return true; } else if(r.end >= l.start && r.end <= l.end){ return true; } return false; }
0
0
Comments
Comments
Satya Pandya2 years ago
Idk why but this post isn't posting the code correctly.
The very top is
mergedIntervals.add(0, intervals.get(0));
intervals.remove(0);
the l=mergedIntervals.get(0);
r=intervalItr.next();,
and on the inside of the if statement it is
mergedIntervals....
On this page