【LeetCode】646. Maximum Length of Pair Chain 解题报告(Python)
作者: 负雪明烛
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:
- 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 日 —— 清明节假期开始,小长假真好~~
最新文章
- 如何在虚拟机里安装Linux
- PC小技巧
- CF723D. Lakes in Berland[DFS floodfill]
- jQuery.extend源码深层分析
- GridView中的GridView1_RowCommand事件
- Linux链接库三(C跟C++之间动态库的相互调用)
- (转)互联网协议入门 ------ HTTP(1)
- IIC总线协议
- VS2010 Command Prompt Error:Cannot determine the location of the VS Common Tools folder
- Zookeeper介绍
- Xamarin.Android 入门实例(4)之实现对 SQLLite 进行添加/修改/删除/查询操作
- 5、判断、循环、数组综合练习案例(迷你DVD)
- linux 网络不通问题排查
- Graph Cuts学习笔记2014.5.16----1
- 设计模式基础:类及类关系的UML表示
- Pytorch如何用预训练模型提取图像特征
- vue与avuex
- 微信小程序访问豆瓣api403问题解决方发法
- Windows10 + IntelliJ IDEA 2017.3.2 + wamp2e + Yii + PHPunit 搭建测试环境
- MySQL索引选择不正确并详细解析OPTIMIZER_TRACE格式