leetcode757 设置交集大小至少为2
给定n个闭区间,求一个集合使得每个区间都至少有两个整数在其中,问集合至少包含多少个元素?
1<=n<=3000; 0<=start[i]<end[i]<=1E8
分析:将区间按end升序、start降序排序,维护集合的最大和次大值,分情况讨论,贪心选择靠右边的点。
class Solution {
public:
    int intersectionSizeTwo(vector<vector<int>>& a) {
        std::sort(a.begin(), a.end(), [](auto& x, auto& y) {
            if (x[1] != y[1])
                return x[1] < y[1];
            return x[0] > y[0];
        });
        int max1 = -1, max2 = -1, ans = 0;
        for (auto x : a) {
            if (x[0] > max1) {
                max1 = x[1];
                max2 = x[1] - 1;
                ans += 2;
            } else if (x[0] > max2) {
                max2 = max1;
                max1 = x[1];
                ans += 1;
            }
        }
        return ans;
    }
};
                    
                
                
            
        
浙公网安备 33010602011771号