算法(十七)贪心问题
2018-01-05 19:06
211 查看
题目描述
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}.
解题思路
将每个[a,b]值按b的值从大到小排列,然后循环每个[a,b]值,这时候有三种情况,下一个对的最小值小于上一个对的b值,所以不需要计算。下一个对的最小值大于上一个对的b值,总数加2,如果等于的话总数加1。代码解析:
class Solution { public: int intersectionSizeTwo(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end(), [](vector<int>& a, vector<int>& b) { return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0]); }); int n = intervals.size(), ans = 0, p1 = -1, p2 = -1; for (int i = 0; i < n; i++) { // current p1, p2 works for intervals[i] if (intervals[i][0] <= p1) continue; // Neither of p1, p2 works for intervals[i] // replace p1, p2 by ending numbers if (intervals[i][0] > p2) { ans += 2; p2 = intervals[i][1]; p1 = p2-1; } // only p2 works; else { ans++; p1 = p2; p2 = intervals[i][1]; } } return ans; } };
相关文章推荐
- 贪心算法之区间覆盖问题
- 贪心算法之用优先队列解决最短路径问题(Dijkstra算法)
- 最简单的贪心算法--删除数字问题
- 贪心算法——区间找点问题
- 贪心算法解决背包问题
- 初入算法篇(贪心) 最多不相交区间问题HDU2037+FOJ1230
- 贪心算法基础之独木舟问题 51nod 贪心教程
- 贪心算法之阿里巴巴与四十大盗(背包问题)
- 贪心算法求解背包问题
- 贪心算法解汽车加油问题
- 贪心算法(二)——一般背包问题
- 贪心算法专题小结——区间相关问题
- 【算法导论】贪心算法之背包问题
- 贪心算法之最大不相交区间数问题
- 贪心算法解决找零钱问题
- 蓝桥杯 算法提高 打水问题 逻辑策略 贪心
- 贪心算法求解问题的选择准则
- 贪心算法一:最优装载问题
- ACM_程序设计竞赛:贪心算法:硬币问题
- 编程之美——买书问题:贪心算法