Leetcode 646. Maximum Length of Pair Chain 找最長鏈 解題報告
阿新 • • 發佈:2018-12-31
這道題麼,找最長的鏈,所謂的鏈就是上一個的結尾一定大於下一個的開頭
因為要找最長的鏈,所以我們按照結尾的那個數字排序,這樣可以儘量的最長
然後從第一個開始,直接往後遍歷找就好,反正在前面的一定是一個最優解(因為不要求區間覆蓋的覆蓋長度,而是要求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;
}
}