LeetCode 题解工作台
合法重新排列数对
给你一个下标从 0 开始的二维整数数组 pairs ,其中 pairs[i] = [start i , end i ] 。如果 pairs 的一个重新排列,满足对每一个下标 i ( 1 )都有 end i-1 == start i ,那么我们就认为这个重新排列是 pairs 的一个 合法重新排列 。…
3
题型
0
代码语言
3
相关题
当前训练重点
困难 · 图·DFS·traversal
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
给你一个下标从 0 开始的二维整数数组 pairs ,其中 pairs[i] = [starti, endi] 。如果 pairs 的一个重新排列,满足对每一个下标 i ( 1 <= i < pairs.length )都有 endi-1 == starti ,那么我们就认为这个重新排列是 pairs 的一个 合法重新排列 。
请你返回 任意一个 pairs 的合法重新排列。
注意:数据保证至少存在一个 pairs 的合法重新排列。
示例 1:
输入:pairs = [[5,1],[4,5],[11,9],[9,4]] 输出:[[11,9],[9,4],[4,5],[5,1]] 解释: 输出的是一个合法重新排列,因为每一个 endi-1 都等于 starti 。 end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3
示例 2:
输入:pairs = [[1,3],[3,2],[2,1]] 输出:[[1,3],[3,2],[2,1]] 解释: 输出的是一个合法重新排列,因为每一个 endi-1 都等于 starti 。 end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 重新排列后的数组 [[2,1],[1,3],[3,2]] 和 [[3,2],[2,1],[1,3]] 都是合法的。
示例 3:
输入:pairs = [[1,2],[1,3],[2,1]] 输出:[[1,2],[2,1],[1,3]] 解释: 输出的是一个合法重新排列,因为每一个 endi-1 都等于 starti 。 end0 = 2 == 2 = start1 end1 = 1 == 1 = start2
提示:
1 <= pairs.length <= 105pairs[i].length == 20 <= starti, endi <= 109starti != endipairs中不存在一模一样的数对。- 至少 存在 一个合法的
pairs重新排列。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(V + E) |
| 空间 | O(V + E) |
面试官常问的追问
外企场景- question_mark
Check if the candidate understands the problem as a graph traversal challenge.
- question_mark
Look for familiarity with Eulerian path conditions and how to apply them in DFS.
- question_mark
Evaluate the candidate's ability to handle large inputs efficiently, ensuring time complexity constraints are respected.
常见陷阱
外企场景- error
Forgetting to handle nodes with no outgoing edges or incoming edges can lead to an incomplete traversal.
- error
Not considering the graph construction properly might make the DFS traversal invalid.
- error
Failing to efficiently handle large inputs within the time constraints can lead to performance issues.
进阶变体
外企场景- arrow_right_alt
If the input allows for multiple valid arrangements, ensure that the algorithm can return any valid solution.
- arrow_right_alt
Variants may ask for optimizations based on specific graph properties or constraints, such as disallowing certain types of pair connections.
- arrow_right_alt
In some variations, the problem might involve finding an arrangement that minimizes or maximizes certain properties, such as the number of hops between nodes.