Problem

Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals (merge if necessary).

Example :
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

JavaScript code

var Interval = function (s, e) {
    this.start = s;
    this.end = e;
}
 
function insert(intervals, newInterval) {
  var result = [];
 
  for(var i=0; i<intervals.length; i++){
      var interval = intervals[i];
        if(interval.end < newInterval.start){
              result.push(interval);
        }else if(interval.start > newInterval.end){
              result.push(newInterval);
              newInterval = interval;        
        }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){
              newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end));
        }
  }
 
  result.push(newInterval); 
 
  return result;
}

var intevs = [new Interval(1,3), new Interval(7,10), new Interval(9,15)];

console.log(insert(intevs, new Interval(3,5)));

1 comment:

  1. TT01001 - Alfa Chemistry is a global leading supplier of analytical chemistry reagents, providing a wide range of analytical chemicals for a variety of analytical applications. With an eternal pursuit of wining customer satisfaction and trust, Alfa Chemistry enjoys a high reputation in product quality and after-sales service. We will continue to work tirelessly to provide our customers with better quality products and more perfect service system.

    ReplyDelete

Blogroll

Popular Posts