- 646. Maximum Length of Pair Chai
- 646. Maximum Length of Pair Chai
- 646. Maximum Length of Pair Chai
- Leetcode 646. Maximum Length of
- Leetcode 646. Maximum Length of
- LeetCode 646. Maximum Length of
- Leetcode 646. Maximum Length of
- Maximum Length of Pair Chain解题报告
- 2020-05-11 646. Maximum Length o
- LeetCode #1239 Maximum Length of
https://leetcode.com/problems/maximum-length-of-pair-chain/description/
解题思路:
- 先对数组排序(根据第一个数字),set pre = Integer.MIN_VALUE;
2.if(pairs[i][0] > pre)
len++;
pre = pairs[i][1];
else if(pre > pairs[i][1]){
pre = pairs[i][1];
}
代码如下:
class Solution {
public int findLongestChain(int[][] pairs) {
/**first method with dp**/
// if(pairs == null || pairs.length == 0) return 0;
// Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
// int len = pairs.length;
// int[] dp = new int[len];
// Arrays.fill(dp, 1);
// int res = 1;
// for (int i = 1; i < len; i++){
// for(int j = 0; j < i; j++){
// if(pairs[i][0] > pairs[j][1])
// dp[i] = Math.max(dp[i], dp[j] + 1);
// }
// res = Math.max(dp[i], res);
// }
// return res;
int len = 0;
Arrays.sort(pairs, (a,b)->(a[0] - b[0]));
int pre = Integer.MIN_VALUE;
for (int i = 0; i < pairs.length; i++){
if(pairs[i][0] > pre){
len++;
pre = pairs[i][1];
}else if(pre > pairs[i][1]){
pre = pairs[i][1];
}
}
return len;
}
}
网友评论