LintCode 1668: Interval Minimum Coverage (Greedy算法典型题)

  1. Interval Minimum Coverage
    cat-only-icon
    CAT Only
    中文English
    There are n intervals in number axis. Now we need to choose some points to make that there is at least one point in each interval.

Return the minimum number of chosen points.

Example
Example 1:

Input: [(1,5), (4,8), (10,12)]
Output: 2
Explanation:
Choose two points: 5, 10
The first interval [1, 5] contains 5
The second interval [4, 8] contains 5
The third interval [10, 12] contains 10
Example 2:

Input: [(1,5), (4,8), (5,12)]
Output: 1
Explanation: All intervals contain 5
Notice
1 <= n <= 10^4
We guarantee that the given intervals are valid and the left and right endpoints of each interval are within the range of [0, 10 ^ 5].
They are closed intervals.

解法1:Greedy。
代码如下:

/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */

struct cmp {
    bool operator() (Interval & a, Interval & b) {
        if (a.start < b.start) return true;
        if (a.start == b.start) return a.end < b.end;
        return false;
    }
}compare;

class Solution {
public:
    /**
     * @param a: the array a
     * @return: return the minimal points number
     */
    int getAns(vector<Interval> &a) {
        int n = a.size();
        if (n == 0) return 0;
        sort(a.begin(), a.end(), compare);
        int result = 1;
        int rangeLeft = a[0].start;
        int rangeRight = a[0].end;
        
        for (int i = 1; i < n; ++i) {
            if (a[i].start <= rangeRight) {
                rangeRight = min(a[i].end, rangeRight);
            } else {
                result++;
                rangeLeft = a[i].start;
                rangeRight = a[i].end;
            }
            
        }
        
        return result;
    }
private:
    bool isOverlapping(Interval & a, Interval & b) {
        if (a.end >= b.start && a.end <= b.end) return true;
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值