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:
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
Link:
https://leetcode.com/contest/leetcode-weekly-contest-42/problems/maximum-length-of-pair-chain/
解題方法:
假設(shè)pairs中有元素pairs[min].[1]是整個pairs中最小的奏候,那么這個元素能接上多少元素就是這道題所求的值扭屁。
所以應(yīng)該先把數(shù)組按照每個元素的第二位數(shù)做ascend排序踏堡。
然后再遍歷數(shù)組尋找能接上鏈子的元素,每次找到一個都要更新最小的第二位數(shù)的值。
當(dāng)有兩個元素出現(xiàn)交錯情況比如:(6, 8) 和 (4, 10),因?yàn)槲覀兘?jīng)過了排序,所以能保證當(dāng)有這種交錯元素的時候耕餐,我們總會取到最小的第二位數(shù)也就是8。而剩下的元素(4, 10)并不會進(jìn)入鏈子辟狈。
Time Complexity:
O(NlogN)
完整代碼:
int findLongestChain(vector<vector<int>>& pairs)
{
if(pairs.size() < 2)
return 0;
sort(pairs.begin(), pairs.end(), [] (vector<int> a, vector<int> b){
return a[1] < b[1];
});
int len = 1;
int min = pairs[0][1];
for(auto a: pairs)
{
if(a[0] > min)
{
len++; //鏈子長度++
min = a[1]; //更新
}
}
return len;
}