leetcode 757. Set Intersection Size At Least Two

该博客探讨了如何找到一个最小的集合S,使得对于给定的所有连续整数区间A,S与A的交集至少包含2个元素。并提供了两个示例说明问题,以及指出解题思路引用了grandyang的详细分析。
摘要由CSDN通过智能技术生成

An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b.

Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has size at least 2.

Example 1:

Input: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
Output: 3
Explanation:
Consider the set S = {2, 3, 4}.  For each interval, there are at least 2 elements from S in the interval.
Also, there isn't a smaller size set that fulfills the above condition.
Thus, we output the size of this set, which is 3.

 

Example 2:

Input: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
Output: 5
Explanation:
An example of a minimum sized set is {1, 2, 3, 4, 5}.

 

Note:

  1. intervals will have length in range [1, 3000].
  2. intervals[i] will have length 2, representing some integer interval.
  3. intervals[i][j] will be an integer in [0, 10^8].

解题思路:

最近懒得写分析了,grandyang大神的分析十分详细,思路差不多 ;

class Solution {
public:
    int intersectionSizeTwo(vector<vector<int>>& intervals) 
    {
        sort(intervals.begin() , intervals.end() , 
             [](vector<int> &a , vector<int> &b){if(a[1] == b[1]) return a[0] > b[0] ;
                                                else return a[1] < b[1] ;} )   ;
        vector<int> res ;
        
        for(auto inter : intervals)
        {
            int cnt = 0 ;
            for(int j = res.size() - 1 ; j >= 0 ; --j)
            {
                if(res[j] >= inter[0] && res[j] <= inter[1]) cnt++ ;
                if(cnt == 2) break ;
            }
            if(cnt == 0) 
            {
                res.push_back(inter[1] - 1) ;
                res.push_back(inter[1]) ;
            }
            else if(cnt == 1)
            {
                res.push_back(inter[1]) ;
            }
        }
        
        return res.size() ;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值