LeetCode646. 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.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;
    }
};
相关推荐
我也不曾来过116 分钟前
list底层原理
数据结构·c++·list
A charmer23 分钟前
C++ 日志系统实战第三步:熟悉掌握各种设计模式
c++·日志系统
农民也会写代码24 分钟前
dedecms织梦arclist标签noflag属性过滤多个参数
开发语言·数据库·sql·php·dedecms
Ethon_王32 分钟前
STL容器适配器详解:queue篇
c++
静听夜半雨36 分钟前
CANoe入门——3、新建LIN工程及LIN DataBase(LDF文件)的创建
网络·数据库·c++·编辑器
内网渗透42 分钟前
Python 虚拟环境管理:venv 与 conda 的选择与配置
开发语言·python·conda·虚拟环境·venv
梁下轻语的秋缘1 小时前
每日c/c++题 备战蓝桥杯 ([洛谷 P1226] 快速幂求模题解)
c++·算法·蓝桥杯
CODE_RabbitV1 小时前
【深度强化学习 DRL 快速实践】逆向强化学习算法 (IRL)
算法
每次的天空2 小时前
kotlin与MVVM结合使用总结(三)
开发语言·microsoft·kotlin
虾球xz2 小时前
游戏引擎学习第244天: 完成异步纹理下载
c++·学习·游戏引擎