LeetCode 题解工作台
合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例 1: 输入: l1 = [1,2,4], l2 = [1,3,4] 输出: [1,1,2,3,4,4] 示例 2: 输入: l1 = [], l2 = [] 输出: [] 示例 3: 输入: l1…
2
题型
10
代码语言
3
相关题
当前训练重点
简单 · 链表指针操作
答案摘要
我们先判断链表 和 是否为空,若其中一个为空,则返回另一个链表。否则,我们比较 和 的头节点: - 若 的头节点的值小于等于 的头节点的值,则递归调用函数 $mergeTwoLists(l_1.next, l_2)$,并将 的头节点与返回的链表头节点相连,返回 的头节点。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50] -100 <= Node.val <= 100l1和l2均按 非递减顺序 排列
解题思路
方法一:递归
我们先判断链表 和 是否为空,若其中一个为空,则返回另一个链表。否则,我们比较 和 的头节点:
- 若 的头节点的值小于等于 的头节点的值,则递归调用函数 ,并将 的头节点与返回的链表头节点相连,返回 的头节点。
- 否则,递归调用函数 ,并将 的头节点与返回的链表头节点相连,返回 的头节点。
时间复杂度 ,空间复杂度 。其中 和 分别为两个链表的长度。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
if list1 is None or list2 is None:
return list1 or list2
if list1.val <= list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1, list2.next)
return list2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of pointer manipulation and its impact on time and space complexity.
- question_mark
Evaluate the candidate's grasp of recursion and how it compares to iteration in this context.
- question_mark
Assess the candidate's ability to handle edge cases, such as empty lists or lists of different lengths.
常见陷阱
外企场景- error
Failing to handle the case where one list is empty.
- error
Incorrectly managing pointer updates when merging nodes.
- error
Not optimizing for space by using an iterative approach when recursion could lead to stack overflow.
进阶变体
外企场景- arrow_right_alt
Merging more than two lists.
- arrow_right_alt
Merging lists of different sizes while maintaining performance.
- arrow_right_alt
Handling negative numbers or different data types in the nodes.