646. Maximum Length of Pair Chain
来源:互联网 发布:苹果a1530支持什么网络 编辑:程序博客网 时间:2024/05/16 02:45
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].
思路:排序后(这样才能确保顺序是对的)找最长递增子数组(这一步可以用二分优化)
也可以按照pair的end来排,就想course schedule一样,优先考end更小的,
import java.util.Arrays;import java.util.Comparator;public class Solution { public int findLongestChain(int[][] pairs) { Arrays.sort(pairs, new Comparator<int[]>(){@Overridepublic int compare(int[] o1, int[] o2) {if(o1[0] == o2[0])return o1[1]-o2[1];return o1[0] - o2[0];} }); int ret = 1; int[] dp = new int[pairs.length]; dp[0] = 1; for(int i=1; i<pairs.length; i++) { dp[i] = 1; for(int j=0; j<i; j++) { if(pairs[j][1] < pairs[i][0]) dp[i] = Math.max(dp[i], dp[j]+1); } ret = Math.max(ret, dp[i]); } return ret; }}
public int findLongestChain(int[][] pairs) { Arrays.sort(pairs, (a,b) -> a[1] - b[1]); int sum = 0, n = pairs.length, i = -1; while (++i < n) { sum++; int curEnd = pairs[i][1]; while (i+1 < n && pairs[i+1][0] <= curEnd) i++; // 选其他的还不如选当前为i的呢 } return sum;}
阅读全文
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
- 信源第二次作业
- CodeForces
- Linux 系统文件属性与权限
- 对称加密和非对称加密的详细说明
- 机器学习框架(长期更新)
- 646. Maximum Length of Pair Chain
- css之BFC
- Plupload插件
- R-CNN之前的准备:Efficient Graph-Based Image Segmentation
- 整数奇偶排序
- 1036. 跟奥巴马一起编程
- 前端浅接触——第一次制作网页
- 第一行代码 第10章 服务 -- 生命周期
- poj 2935 Basic Wall Maze bfs+路径记录