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}.

Note:

  1. intervals will have length in range [1, 3000].
  2. intervals[i] will have length 2, representing some integer interval.
  3. intervals[i][j] will be an integer in [0, 10^8].
 

Approach #1: C++. [greedy]

class Solution {
public:
int intersectionSizeTwo(vector<vector<int>>& intervals) {
int size = intervals.size();
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
if (a[1] == b[1]) return a[0] > b[0];
else return a[1] < b[1];
}); int ans = 0, p1 = -1, p2 = -1;
for (int i = 0; i < size; ++i) {
if (intervals[i][0] <= p1) continue;
if (intervals[i][0] > p2) {
ans += 2;
p2 = intervals[i][1];
p1 = p2 - 1;
} else {
ans++;
p1 = p2;
p2 = intervals[i][1];
}
} return ans;
}
};

  

最新文章

  1. Entity Framework 6 Recipes 2nd Edition(9-5)译-&gt;删除一个断开的实体
  2. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
  3. [DPDK][转]DPDK编程开发(4)—lcore
  4. 【Visual Lisp】块专题
  5. ios-chart 不支持渐变的底色 --- 后面支持了渐变
  6. maven本地仓库
  7. NDK中, 如何提高脚本式语言的可读性
  8. clients(PV操作共享内核内存进行输入输出分屏) - server(进程间通信)模型实现
  9. ☀【offset() / position()】
  10. 支持“***Context”上下文的模型已在数据库创建后发生更改。请考虑使用 Code First 迁移更新数据库(http://go.microsoft.com/fwlink/?LinkId=238269)。
  11. SQL Server高可用——日志传送(4-2)——部署
  12. php短数组写法
  13. Java加密与解密笔记(三) 非对称加密
  14. 分享html5的一个拖拽手法
  15. 在Qt中配置TBB以及简单实用
  16. linux抓包工具Charles的配置安装
  17. abp Cannot access a disposed object. A common cause of this error is disposing
  18. Netsharp总体设计
  19. VirtualBox 报错VERR_VD_IMAGE_READ_ONLY
  20. linux下gzip的压缩详解

热门文章

  1. Java开发需要注意的流程
  2. Linux - apache 服务
  3. shulti模块简述
  4. 一只小蜜蜂(斐波那契dp)
  5. /error处理
  6. c# 如何制作RealPlayer 视频播放器
  7. 2.Hive的几种常见的数据导入方式
  8. lnmp+laravel部署到服务器出现 &quot;GET / HTTP/1.1&quot; 500 5
  9. Flask框架 之 wtforms
  10. mybatis 获得一个map的返回集合