646. Maximum Length of Pair Chain
来源:互联网 发布:孝庄文皇后 知乎 编辑:程序博客网 时间:2024/06/05 10:53
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: 2Explanation: The longest chain is [1,2] -> [3,4]
Note:
- The number of given pairs will be in the range [1, 1000].
分析
按照第二个元素的大小对pairs进行排序。最长链是以第一个pair开始的,遍历,记录下每次”follow“的pair的第二个元素为pre,计数。
code
#include <iostream>#include<algorithm>#include<vector> using namespace std;class Solution {public: int findLongestChain(vector<vector<int> >& pairs) { sort(pairs.begin(),pairs.end(),compare); int count=0, pre; for (int i = 0; i < pairs.size(); ++i) { if(i==0) { count++; pre=pairs[i][1]; } if (pairs[i][0] > pre) { count++; pre=pairs[i][1]; } } return count; } static bool compare(vector<int> a, vector<int> b) {if (a[1]==b[1])return a[0] < b[0];else return a[1]<b[1];}};
阅读全文
0 0
- 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- [leetcode]646. Maximum Length of Pair Chain
- leetcode 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- LeetCode 646. Maximum Length of Pair Chain
- [Leetcode] 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- leetcode 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- [leetcode] 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain(M)
- [LeetCode] 646. Maximum Length of Pair Chain
- [LeetCode] 646. Maximum Length of Pair Chain
- 646. Maximum Length of Pair Chain
- LeetCode 646. Maximum Length of Pair Chain
- mysql创建定时器(event),查看定时器,打开定时器,设置定时器时间
- SDN:openflow1.3英文版单词整理
- Onvif学习笔记3
- POJ 1286Necklace of Beads
- 使用不可靠的UDP设计可靠的文件传输协议
- 646. Maximum Length of Pair Chain
- 软件需求工程 课堂笔记11
- 关于properties空指针报错的问题 java.lang.NullPointerException
- Java操作桌面应用 --- Desktop 类
- 手机QQ邮箱登录不上的解决办法
- 用于图像分割的卷积神经网络:从R-CNN到Mask R-CNN
- 个人总结26
- shader总结五
- Spark开发-Yarn cluster模式