Leetcode 435 Solution

This article provides solution to leetcode question 435 (non-overlapping-intervals)

https://leetcode.com/problems/non-overlapping-intervals

Solution

/**
 * 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) {
        vector<Interval>& a = intervals;

        sort(a.begin(), a.end(), [] (const Interval& lhs, const Interval& rhs) {return lhs.start < rhs.start;});

        int res = 0;
        int last = 0;

        for (int i = 1; i < a.size(); i++)
        {
            if (a[i].start < a[last].end)
            {
                res++;

                if (a[i].end < a[last].end)
                    last = i;
            }
            else
                last = i;
        }

        return res;
    }
};