435. Non-overlapping interval (greedy)

Given a set of intervals, find the minimum number of intervals that need to be removed so that the remaining intervals do not overlap each other.

note:

It can be considered that the end of an interval is always greater than its starting point.
The boundaries of the intervals [1,2] and [2,3] "touch" each other, but do not overlap each other.
Example 1:

Input: [[1,2], [2,3], [3,4], [1,3]]

Output: 1

Explanation: After removing [1,3], the remaining intervals do not overlap.
Example 2:

Input: [[1,2], [1,2], [1,2]]

Output: 2

Explanation: You need to remove the two [1,2] so that the remaining intervals do not overlap.

analysis:

This problem is almost the same as 452. Use the fewest arrows to detonate the balloon . First arrange the order by the key position of the abscissa, then traverse the ordered intervals from front to back, and erase the traversed element when it encounters overlaps, because it In the middle of i-1 and i+1, greedy thinking is also used here. If you wipe the middle, the distance between the two passes will be longer, and the overlap will be less likely to occur. The difference from the problem of shooting a balloon is that they are both encounters. Add 1 to the overlapping count (this question), and add 1 to the count that does not overlap (shoot a balloon)

class Solution {
    
    
public:
    static bool compare(vector<int>& m, vector<int>& n){
    
    
        if(m[1] == n[1]) return m[0] < n[0];
        else return m[1] < n[1];
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
    
    
        if(intervals.size() < 2) return 0;
        sort(intervals.begin(), intervals.end(), compare);
        int eraseTimes = 0;
        int maxLocation = intervals[0][1];
        for(int i = 1; i < intervals.size(); ++i){
    
    
            if(maxLocation > intervals[i][0]){
    
    
                ++eraseTimes;
            }else{
    
    
                maxLocation = intervals[i][1];
            }
        }

        return eraseTimes;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113880922