JAVASCRIPT Leetcode435. Non-overlapping Intervals

435. Non-overlapping Intervals

题目
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:

Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

关键词: greedy, 2D array, sort
思路

  1. 按照内嵌数组[1] 进行排序,因为这样能让范围更大的内嵌数组涵盖更多的数组,减少剔除重复区间的次数。
  2. 建一个flag作为区间指标,如果接下的数组有和flag重合,count++;否则更新flag。

解题:时间复杂度: O(nlogn);空间复杂度:O(1)

var eraseOverlapIntervals = function(intervals) {
   if (!intervals || !intervals[0] || intervals.length == 0 || intervals[0].length == 0) return 0;
   intervals.sort((n1, n2) => {
       return n1[1] - n2[1]; //sort by [1] rather [0] can see larger range will overlap, since we wanna remove minimum.
   });
   let count = 0;
   let flag = [intervals[0][0], intervals[0][1]];
   for (let i = 1; i < intervals.length; i++){
       if (flag[1] > intervals[i][0]) {  //already sorted, so only think [0]
           count++;
       }
       else{//update flag
           flag = [intervals[i][0], intervals[i][1]];
       }   
   }
   return count;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值