Leetcode 435. Non-overlapping Intervals 无交叉覆盖区间 解题报告

1 解题思想

题目给了一堆区间[起始位置,结束位置]
这些区间可能会有一些交叠的地方(边界相邻不算),现在要求找到一个方法,可以做最少的删除动作,使得剩下的区间都不交叉覆盖,返回那个需要删除的最少次数

解题思想(贪心法):
1、按照起始位置排序
2、按照顺序,两个指针遍历,一前一后,如果当前位置和上一个位置不冲突就顺序平移两个指针(后指针的值给前指针,然后后指针移动到下一位),如果冲突的话,那么前指针则变成当前两个指针当中覆盖最小的一个(贪心所在),后指针移动到下一个位置就好

2 原题

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals 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.

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.

3 AC解

/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */
public class Solution {
    public int eraseOverlapIntervals(Interval[] intervals) {
        // 按照起始位置进行排序
        Arrays.sort(intervals,(x,y)->(x.start)-(y.start));
        int count=0,j=0;
        // 贪心法,如果上一个位置j和当前位置i冲突了,那么进行判断,如果当前位置的末尾小于上一个边界的末尾,那么删除上一个位置(因为覆盖的更少,每步选择最有可能不造成重复的),反之如果当前位置尾部覆盖的更多,那么就删除i的位置。删除的方式通过控制j的取值进行
        for(int i=1;i<intervals.length;i++) {
            if(intervals[j].end>intervals[i].start){
                j=intervals[i].end<intervals[j].end?i:j;
                count++;
            }else
            //没有重复
                j=i;

        }
        return count;

    }
}

你可能感兴趣的:(LeetCode,遍历,移动,指针,贪心法)