美文网首页
Maximum Length of Pair Chain解题报告

Maximum Length of Pair Chain解题报告

作者: 黑山老水 | 来源:发表于2017-07-24 11:01 被阅读110次

    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:

    Input: [[1,2], [2,3], [3,4]]
    Output: 2
    Explanation: The longest chain is [1,2] -> [3,4]

    Link:

    https://leetcode.com/contest/leetcode-weekly-contest-42/problems/maximum-length-of-pair-chain/

    解题方法:

    假设pairs中有元素pairs[min].[1]是整个pairs中最小的,那么这个元素能接上多少元素就是这道题所求的值。
    所以应该先把数组按照每个元素的第二位数做ascend排序。
    然后再遍历数组寻找能接上链子的元素,每次找到一个都要更新最小的第二位数的值。
    当有两个元素出现交错情况比如:(6, 8) 和 (4, 10),因为我们经过了排序,所以能保证当有这种交错元素的时候,我们总会取到最小的第二位数也就是8。而剩下的元素(4, 10)并不会进入链子。

    Time Complexity:

    O(NlogN)

    完整代码:

    int findLongestChain(vector<vector<int>>& pairs) 
        {
            if(pairs.size() < 2)
                return 0;
            sort(pairs.begin(), pairs.end(), [] (vector<int> a, vector<int> b){
                return a[1] < b[1];
            });
            int len = 1;
            int min = pairs[0][1];
            for(auto a: pairs)
            {
                if(a[0] > min)
                {
                    len++; //链子长度++
                    min = a[1]; //更新
                }
            }
            return len;
        }
    

    相关文章

      网友评论

          本文标题:Maximum Length of Pair Chain解题报告

          本文链接:https://www.haomeiwen.com/subject/lzavkxtx.html