栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode-646. Maximum Length of Pair Chain [C++][Java]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode-646. Maximum Length of Pair Chain [C++][Java]

LeetCode-646. Maximum Length of Pair Chainhttps://leetcode.com/problems/maximum-length-of-pair-chain/

题目描述

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

Example 1:

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

Example 2:

Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].

Constraints:

n == pairs.length1 <= n <= 1000-1000 <= lefti < righti <= 1000

解题思路 【C++】
class Solution {
public:
    int findLongestChain(vector>& pairs) {
        if (pairs.empty()) {return 0;}
        auto cmp = [](const vector  &a, const vector  &b){
            return a[1] < b[1];
        };
        sort(pairs.begin(), pairs.end(), cmp);
        int ans = 1, e = pairs[0][1];
        for (int i = 1; i < pairs.size(); i++) {
            if (pairs[i][0] > e) {
                ans++;
                e = pairs[i][1];
            } else {e = min(e, pairs[i][1]);}
        }
        return ans;
    }
};

【Java】
class Solution {
    public int findLongestChain(int[][] pairs) {
        if (pairs.length == 0 || pairs[0].length == 0) {return 0;}
        Arrays.sort(pairs, (a, b) -> {return a[1] - b[1];});
        int ans = 1, e = pairs[0][1];
        for (int i = 1; i < pairs.length; i++) {
            if (pairs[i][0] > e) {
                ans++;
                e = pairs[i][1];
            } else {e = Math.min(e, pairs[i][1]);}
        }
        return ans;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号