leetcode 435. Non-overlapping Intervals

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
static bool cmp(const Interval& a, const Interval& b){
    return a.end < b.end;
}
class Solution {// 贪心算法
public:
    int eraseOverlapIntervals(vector<Interval>& intervals) {
        if (intervals.empty())
            return 0;
        sort(intervals.begin(), intervals.end(),cmp);
        int ret = 0;
        int prior_end = intervals[0].end;
        for (int i = 1 ; i < intervals.size(); ++i){
            if (intervals[i].start < prior_end)
                ret++;
            else
                prior_end = intervals[i].end;
        }
        return ret;
    }
};

点赞