zoukankan      html  css  js  c++  java
  • [LintCode 1668.] 区间最小覆盖

    1668. 区间最小覆盖
    CAT 专属题目

    数轴上有 n 个区间. 现在需要在数轴上选取一些点, 使得任意一个区间内至少包含一个点.

    返回最少选取的点的数目.

    样例
    样例 1:

    输入: [(1,5), (4,8), (10,12)]
    输出: 2
    解释:
    选择两个点: 5, 10
    第一个区间 [1, 5] 包含了 5
    第二个区间 [4, 8] 包含了 5
    第三个区间 [10, 12] 包含了 10
    样例 2:

    输入: [(1,5), (4,8), (5,12)]
    输出: 1
    解释: 所有区间都包含 5
    注意事项

    1. 1 <= n <= 10^4
    2. 保证给定的区间合法, 且区间左右端点在[0, 10^5] 范围内
    3. 给定的都是闭区间

    按照开始时间排序选结束时间点,会漏掉开始晚结束早的。比如[(1,4),(2,3),(4,6)],按开始时间排序后,第一次选的是4,跳过第二个区间,判断第三个区间也能覆盖,得到答案为1。实际上第二个区间被忽视了,4这个点并不能覆盖(2,3)这个区间。
    按照结束时间排序选结束时间点就没问题了。

    /**
     * Definition of Interval:
     * classs Interval {
     *     int start, end;
     *     Interval(int start, int end) {
     *         this->start = start;
     *         this->end = end;
     *     }
     * }
     */
    
    class Solution {
    public:
        /**
         * @param a: the array a
         * @return: return the minimal points number
         */
        int getAns(vector<Interval> &a) {
            // write your code here
            if (a.empty()) return 0;
            std::sort(a.begin(), a.end(), cmp);
            int res = 1;
            int selected = a[0].end;
            for (int i=1; i<a.size(); i++) {
                if (a[i].start <= selected) continue;
                else {
                    selected = a[i].end;
                    res++;
                }
            }
            return res;
        }
        static bool cmp(const Interval& lhs, const Interval& rhs) {
            if (lhs.end != rhs.end)
                return lhs.end < rhs.end;
            return lhs.start < rhs.start;
        }
    };
    
  • 相关阅读:
    文件系统
    MySQL中添加唯一约束和联合唯一约束
    Ubuntu(Debian)的aptitude与apt-get的区别和联系
    透明与Z序示例
    Qt Quick分组属性案例
    TextView 设置超过几行后显示省略号
    ionic list item-radio checked
    webkit的基本应用
    信号槽操作案例
    报错:tr was not declared in this scope
  • 原文地址:https://www.cnblogs.com/zhcpku/p/14258752.html
Copyright © 2011-2022 走看看