前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >757. Set Intersection Size At Least Two

757. Set Intersection Size At Least Two

作者头像
用户7886150
修改2021-01-26 10:30:02
2950
修改2021-01-26 10:30:02
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Python Set intersection()

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: 

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

class Solution {

    public int intersectionSizeTwo(int[][] intervals) {

        Arrays.sort(intervals, (a, b) ->

                    a[0] != b[0] ? a[0]-b[0] : b[1]-a[1]);

        int[] todo = new int[intervals.length];

        Arrays.fill(todo, 2);

        int ans = 0, t = intervals.length;

        while (--t >= 0) {

            int s = intervals[t][0];

            int e = intervals[t][1];

            int m = todo[t];

            for (int p = s; p < s+m; ++p) {

                for (int i = 0; i <= t; ++i)

                    if (todo[i] > 0 && p <= intervals[i][1])

                        todo[i]--;

                ans++;

            }

        }

        return ans;

    }

}

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档