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:

  1. 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;}