- 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;
}
};
本文探讨了在数轴上给定多个区间的情况下,如何选择最少的点数,确保每个区间至少包含一个点。通过两个实例说明了算法的运行过程,并提供了一种贪婪算法的实现方式,用于解决此问题。
5万+

被折叠的 条评论
为什么被折叠?



