算法笔记30:无重叠区间

213 阅读1分钟

435. 无重叠区间

不管有多少个重叠的区间,我们可以通过找到所有区间中,那些不相交的,然后用总个数减去这些本来就不相交的,就得到了要删除的数量。而要让被删除的数量尽可能小,只能是尽可能多的找到那些不相交的区间。

这里的贪心思路是将所有区间按照由端点进行排序,这样做可以让每个区间的左端点尽可能的靠前,而带来的好处就是可以在快速的排除掉会重叠的区间的同时,保证每个不重叠区间我们都可以访问到。

代码如下:

const eraseOverlapIntervals = (intervals) => {
    const len = intervals.length;
    // sort with right point value
    intervals.sort((a, b) => a[1] - b[1]);
    
    let count = 1;
    // initial with first interval
    let rightMost = intervals[0][1];
    for (let i = 1; i < len; i++) {
        // for each interval, if the left point is not overlapping
        // with last right most point, then this interval is the
        // next non-overlapping one, increment the counter and 
        // update the value for next comparison
        if (intervals[i][0] >= rightMost) {
            count++;
            rightMost = intervals[i][1];
        }
    }
    
    // the answer is the subtraction of the total value by the non-overlapping ones
    return len - count; 
};