LeetCode 题解工作台

最长数对链

给你一个由 n 个数对组成的数对数组 pairs ,其中 pairs[i] = [left i , right i ] 且 left i i 。 现在,我们定义一种 跟随 关系,当且仅当 b 时,数对 p2 = [c, d] 才可以跟在 p1 = [a, b] 后面。我们用这种形式来构造 数对链 。…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们将所有数对按照第二个数的升序排序,用一个变量 维护已经选择的数对的第二个数的最大值。 遍历排序后的数对,如果当前数对的第一个数大于 ,那么我们可以贪心地选择当前数对,答案加一,并将 更新为当前数对的第二个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 n 个数对组成的数对数组 pairs ,其中 pairs[i] = [lefti, righti] 且 lefti < righti

现在,我们定义一种 跟随 关系,当且仅当 b < c 时,数对 p2 = [c, d] 才可以跟在 p1 = [a, b] 后面。我们用这种形式来构造 数对链

找出并返回能够形成的 最长数对链的长度

你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。

 

示例 1:

输入:pairs = [[1,2], [2,3], [3,4]]
输出:2
解释:最长的数对链是 [1,2] -> [3,4] 。

示例 2:

输入:pairs = [[1,2],[7,8],[4,5]]
输出:3
解释:最长的数对链是 [1,2] -> [4,5] -> [7,8] 。

 

提示:

  • n == pairs.length
  • 1 <= n <= 1000
  • -1000 <= lefti < righti <= 1000
lightbulb

解题思路

方法一:排序 + 贪心

我们将所有数对按照第二个数的升序排序,用一个变量 pre\textit{pre} 维护已经选择的数对的第二个数的最大值。

遍历排序后的数对,如果当前数对的第一个数大于 pre\textit{pre},那么我们可以贪心地选择当前数对,答案加一,并将 pre\textit{pre} 更新为当前数对的第二个数。

遍历结束后,返回答案即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数对的数量。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs.sort(key=lambda x: x[1])
        ans, pre = 0, -inf
        for a, b in pairs:
            if pre < a:
                ans += 1
                pre = b
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on sorting pairs by the second element to simplify chain selection.

  • question_mark

    Expect a DP or greedy approach based on the state transition dynamic programming pattern.

  • question_mark

    Be prepared to discuss time vs space trade-offs between O(n^2) DP and O(n log n) greedy solution.

warning

常见陷阱

外企场景
  • error

    Failing to sort pairs first can lead to incorrect chain lengths.

  • error

    Incorrectly updating DP table without checking b < c condition.

  • error

    Mixing up greedy selection order can produce invalid chains.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the longest decreasing chain by reversing pair comparisons.

  • arrow_right_alt

    Allow overlapping chains and count maximum compatible subsets instead of strict chains.

  • arrow_right_alt

    Extend to 3D triplets where each subsequent element must be larger in all dimensions.

help

常见问题

外企场景

最长数对链题解:状态·转移·动态规划 | LeetCode #646 中等