LeetCode Maximum Length of Pair Chain

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Maximum Length of Pair Chain相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

题目:

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

题解:

按照pair的second number 排序pairs. 再iterate pairs, 若当前pair的second number 小于下个pair的first number, 计数sum++, 否则跳过下个pair.

Note: 用curEnd把当前的second number标记出来, 不要用pair[i][1], 否则 i 跳动时就不是当前pair的second number了.

Time Complexity: O(nlogn). n = pairs.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int findLongestChain(int[][] pairs) {
 3         if(pairs == null || pairs.length == 0){
 4             return 0;
 5         }
 6         
 7         int len = pairs.length;
 8         Arrays.sort(pairs, new Comparator<int []>(){
 9             public int compare(int [] a, int [] b){
10                 return a[1] - b[1];
11             }
12         });
13         
14         int i = 0;
15         int sum = 0;
16         while(i<len){
17             sum++;
18             int curEnd = pairs[i][1];
19             while(i+1<len && curEnd>=pairs[i+1][0]){
20                 i++;
21             }
22             i++;
23         }
24         return sum;
25     }
26 }

 

以上是关于LeetCode Maximum Length of Pair Chain的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 718. Maximum Length of Repeated Subarray

LeetCode-718. Maximum Length of Repeated Subarray

[leetcode-646-Maximum Length of Pair Chain]

[LeetCode] Maximum Length of Repeated Subarray 最长的重复子数组

LeetCode 718. 最长重复子数组(Maximum Length of Repeated Subarray)

Leetcode 718. Maximum Length of Repeated Subarray