• 757. Set Intersection Size At Least Two


    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].
     

    Approach #1: C++. [greedy]

    class Solution {
    public:
        int intersectionSizeTwo(vector<vector<int>>& intervals) {
            int size = intervals.size();
            sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
                if (a[1] == b[1]) return a[0] > b[0];
                else return a[1] < b[1];
            });
            
            int ans = 0, p1 = -1, p2 = -1;
            for (int i = 0; i < size; ++i) {
                if (intervals[i][0] <= p1) continue;
                if (intervals[i][0] > p2) {
                    ans += 2;
                    p2 = intervals[i][1];
                    p1 = p2 - 1;
                } else {
                    ans++;
                    p1 = p2;
                    p2 = intervals[i][1];
                }
            }
            
            return ans;
        }
    };
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Js:返回上一页
    select设置选中项/select的级联
    js闭包
    bootstrap
    My97DatePicker使用 、layDate 日期与时间组件
    IO流
    java之String工具类和File类
    Python学习之路文件file常用方法
    Python学习之路-集合set的常用方法
    Python学习之路-字典外传
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10247295.html
Copyright © 2020-2023  润新知