435. Non-overlapping Intervals
https://leetcode.com/problems/non-overlapping-intervals/description/
Greedy. Sort by (start,-end). Scan from left to right, if we see 2 intervals overlap, we should remove the interval with larger end value.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int eraseOverlapIntervals(vector<Interval>& intervals) { if (intervals.size() <= 1) return 0; auto comp = [](const Interval& i1, const Interval& i2) { return i1.start < i2.start || i1.start == i2.start && i1.end > i2.end; }; sort(intervals.begin(), intervals.end(), comp); int res = 0; auto cur = intervals[0]; for (int i = 1; i < intervals.size(); i++) { if (cur.end > intervals[i].start) { res++; if (cur.end > intervals[i].end) { // delete cur cur = intervals[i]; } } else { // no overlap cur = intervals[i]; } } return res; } };