题目要求

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.
Example 3:

Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
 

Note:

You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.

使用二维数组表示区间组,每一个子数组的第一个值表示区间的开始坐标,第二个值表示区间的结束坐标。计算最少进行多少次删除操作,可以确保剩下的区间不会产生任何重叠。

思路和代码

假设有两个区间, 这两个区间之间会存在以下几种关系:

  1. 毫无重叠,此时无需进行删除
  2. 部分重叠。则需要找出和周围区间交叉最少的区间进行保留。如果将区间按照从小到大的次序排列,出现这种情况时,每次都保留前一个区间。
  3. 区间1为区间2的子区间或区间2为区间1的子区间,则保留子区间,删除父区间

代码如下:

    public int eraseOverlapIntervals(int[][] intervals) {
        if(intervals == null || intervals.length == 0) return 0;
        Arrays.sort(intervals, new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                // TODO Auto-generated method stub
                return o1[0] - o2[0] == 0 ? o1[1] - o2[1] : o1[0] - o2[0];
            }
            
        });
        
        int count = 0;
        int end = intervals[0][1];
        for(int i = 1 ; i<intervals.length ; i++) {
            int[] interval = intervals[i];
            if(interval[0] < end) {;
                count++;
                end = Math.min(end, interval[1]);
            }else {
                end = interval[1];
            }
        }
        return count;
    }

raledong
2.7k 声望2k 粉丝

心怀远方,负重前行