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;
    }
};
相关推荐
wo3258661453 分钟前
浪潮交换机配置track检测实现高速公路收费网络主备切换NQA
开发语言·网络·php
豪斯有话说6 分钟前
C++_哈希表
数据结构·c++·散列表
知识中的海王8 分钟前
Python html 库用法详解
开发语言·python
獨枭25 分钟前
配置 macOS 上的 Ruby 开发环境
开发语言·macos·ruby
飞由于度31 分钟前
C#中清空DataGridView的方法
开发语言·c#
jndingxin36 分钟前
OpenCV CUDA模块光流计算-----实现Farneback光流算法的类cv::cuda::FarnebackOpticalFlow
人工智能·opencv·算法
编程绿豆侠1 小时前
力扣HOT100之栈:394. 字符串解码
java·算法·leetcode
real_metrix1 小时前
【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案
c++·迭代器·迭代器失效·erase
朝朝又沐沐1 小时前
基于算法竞赛的c++编程(18)string类细节问题
开发语言·c++·算法
记得早睡~1 小时前
leetcode73-矩阵置零
数据结构·leetcode·矩阵