646. Maximum Length of Pair Chain

Problem:
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:
  1. The number of given pairs will be in the range [1, 1000].

Analysis:
思路很简单几乎是照搬Longest Increasing Subsequence. 区别在于先要把pairs 按照pair[0] 排序。这里我就不懂了,为什么排好序的就可以求出最长chain。 

还有一种解法是按pair[1]排序,如果当前pair[0] > current end, 那么就把这2个pair连起来。个人更喜欢第二种解法。

Solution:

class Solution {
    public int findLongestChain(int[][] pairs) {
        if (pairs == null || pairs[0].length == 0)
            return 0;
        Arrays.sort(pairs, (a,b) -> a[1] - b[1]);
        int res = 0;
        int end = Integer.MIN_VALUE;
        for (int[] p: pairs) {
            if (p[0] > end) {
                res++;
                end = p[1];
            }
        }
        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List