这道题么,找最长的链,所谓的链就是上一个的结尾一定大于下一个的开头
因为要找最长的链,所以我们按照结尾的那个数字排序,这样可以尽量的最长
然后从第一个开始,直接往后遍历找就好,反正在前面的一定是一个最优解(因为不要求区间覆盖的覆盖长度,而是要求pair的数量)
相对的,如果是要找区间最长,应该就是排序后要上DP了,而不是这样直接找
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].
public class Solution {
public int findLongestChain(int[][] pairs) {
//sort
/**
按照截止排序,就可以找到最优的组合方案了
**/
Arrays.sort(pairs, (a,b) -> a[1] - b[1]);
int sum = 0, n = pairs.length;
int i = 0;
while (i < n){
int current_end = pairs[i][1];
sum ++;
while ( i < n && pairs[i][0] <= current_end) i++;
}
return sum;
}
}