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 &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;
    }
};

你可能感兴趣的:(LintCode)