LeetCode 646 Maximum Length of Pair Chain (贪心)

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].


题目分析:经典的贪心问题,按照第二个数字对数组排序,然后按题意尽可能多的取即可,原因很简单,要保证后面尽可能多的取,那么前面也应该尽可能早的结束
class Solution {
    
    public int findLongestChain(int[][] pairs) {
        int n = pairs.length;
        if (n == 1) {
            return 1;
        }

        Arrays.sort(pairs, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });

        int ans = 1, i = 1, r = pairs[0][1];
        while (i < n) {
            while (i < n && pairs[i][0] <= r) {
                i ++;
            }
            if (i == n) {
                break;
            }
            r = pairs[i][1];
            ans ++;
        }
        return ans;
    }
}


猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/78901443