作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

题目描述

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn’t use up all the given pairs. You can select pairs in any order.

Example 1:

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

Note:

  1. The number of given pairs will be in the range [1, 1000].

题目大意

给出了很多区间,找出能够成的连续增长的区间的个数。区间是闭区间,不能有任何重叠。

解题方法

贪心算法

题目给的提示是DP,我用Python的DP竟然超时了。其实我第一想法是贪心算法,在机试指南中的39页,题目是《今年暑假不AC》,原题是能收看到的最多的电视节目的数量。

这题的做法是按照每个区间的右边界进行排序,我们优先选择结束时间最早的区间,这样的贪心做法能保证最后得到的区间的数目是最多的。

Python代码:

class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=lambda x: x[1])
currTime, ans = float('-inf'), 0
for x, y in pairs:
if currTime < x:
currTime = y
ans += 1
return ans

日期

2018 年 4 月 5 日 —— 清明节假期开始,小长假真好~~

最新文章

  1. 如何在虚拟机里安装Linux
  2. PC小技巧
  3. CF723D. Lakes in Berland[DFS floodfill]
  4. jQuery.extend源码深层分析
  5. GridView中的GridView1_RowCommand事件
  6. Linux链接库三(C跟C++之间动态库的相互调用)
  7. (转)互联网协议入门 ------ HTTP(1)
  8. IIC总线协议
  9. VS2010 Command Prompt Error:Cannot determine the location of the VS Common Tools folder
  10. Zookeeper介绍
  11. Xamarin.Android 入门实例(4)之实现对 SQLLite 进行添加/修改/删除/查询操作
  12. 5、判断、循环、数组综合练习案例(迷你DVD)
  13. linux 网络不通问题排查
  14. Graph Cuts学习笔记2014.5.16----1
  15. 设计模式基础:类及类关系的UML表示
  16. Pytorch如何用预训练模型提取图像特征
  17. vue与avuex
  18. 微信小程序访问豆瓣api403问题解决方发法
  19. Windows10 + IntelliJ IDEA 2017.3.2 + wamp2e + Yii + PHPunit 搭建测试环境
  20. MySQL索引选择不正确并详细解析OPTIMIZER_TRACE格式

热门文章

  1. k8s集群中部署Rook-Ceph高可用集群
  2. javaSE高级篇2 — 流技术 — 更新完毕
  3. CR LF 的含义
  4. STL学习笔记1
  5. Oracle—回车、换行符
  6. Virtual functions in derived classes
  7. JPA和事务管理
  8. Java易错小结
  9. SQL Server中修改“用户自定义表类型”问题的分析与方法
  10. ssm+mysql+jsp打造在线考试系统WeKnow-学生端