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;
    }
};
相关推荐
酱酱哥玩AI3 分钟前
Trae编译器:实现多目标班翠鸟优化算法(IPKO)无人机路径规划仿真(Python版),完整代码
算法
du fei9 分钟前
C# 窗体应用(.FET Framework) 线程操作方法
开发语言·c#
du fei10 分钟前
C#文件操作
开发语言·c#
MPCTHU16 分钟前
二叉树、排序算法与结构图
数据结构·算法·排序算法
m0_5557629019 分钟前
struct 中在c++ 和c中用法区别
java·c语言·c++
亓才孓22 分钟前
[leetcode]树的操作
算法·leetcode·职场和发展
月亮有痕迹诶22 分钟前
【C++】智能指针
开发语言·c++·c++11
搞不懂语言的程序员28 分钟前
装饰器模式详解
开发语言·python·装饰器模式
王禄DUT33 分钟前
化学方程式配平 第33次CCF-CSP计算机软件能力认证
开发语言·c++·算法
Yang-Never35 分钟前
Open GL ES ->纹理贴图,顶点坐标和纹理坐标组合到同一个顶点缓冲对象中进行解析
android·java·开发语言·android studio·贴图