Easy Understood C++ Solution (Greedy)


  • 0
    S
    class Solution {
    public:
        int eraseOverlapIntervals(vector<Interval>& intervals) {
            std::sort(intervals.begin(), intervals.end(), 
                        [](const Interval& lhs, const Interval& rhs) {
                            if (lhs.end != rhs.end) {
                                return lhs.end < rhs.end;
                            } else {
                                return lhs.start > rhs.start;
                            }
                        });
                        
            int n = intervals.size(), lastIdx = 0; 
            int result = 0;
            for (int i = 1; i < n; i++) {
                if (intervals[i].start < intervals[lastIdx].end) {
                    result++;
                } else {
                    lastIdx = i;
                }
            }
            return result;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.