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:

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;
    }
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容