LeetCode646. Maximum Length of Pair Chain——动态规划

文章目录

一、题目

You are given an array of n pairs pairs where pairsi = 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.length

1 <= n <= 1000

-1000 <= lefti < righti <= 1000

二、题解

cpp 复制代码
class Solution {
public:
    static bool cmp(vector<int>& a,vector<int>& b){
        return a[0] < b[0];
    }
    int findLongestChain(vector<vector<int>>& pairs) {
        int n = pairs.size(),len = 0;
        sort(pairs.begin(),pairs.end(),cmp);
        vector<int> ends(n,0);
        for(int i = 0;i < n;i++){
            int index = bs(ends,len,pairs[i][0]);
            if(index == -1) ends[len++] = pairs[i][1];
            else ends[index] = min(ends[index],pairs[i][1]);
        }
        return len;
    }
    int bs(vector<int>& ends,int len,int num){
        int l = 0,r = len - 1,res = -1;
        while(l <= r){
            int mid = (l + r) / 2;
            if(ends[mid] >= num){
                res = mid;
                r = mid - 1;
            }
            else l = mid + 1;
        }
        return res;
    }
};
相关推荐
汤姆宝库8 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
武子康9 小时前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
驭渊的小故事10 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
南风841110 小时前
C++ 四种强制类型转换详解
c++
Sakura_j_h_11 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q11 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider199812 小时前
Python基础语法之并发相关3
开发语言·python
FRing0312 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
文丑颜不良啊12 小时前
LeetCode3001~3020题目解析
java·leetcode
CS_Zero13 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek