leetcode 第21题
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例2 :
输入:l1 = [], l2 = [0]
输出:[0]
关键词:链表、迭代、递归。
迭代解法:
迭代思路详见注释,注意循环不变量的设置:list1和list2中选取小的为list3下一节点。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode list1 = l1;
ListNode list2 = l2;
// 虚构头节点,方便返回结果。
ListNode target = new ListNode(-1);
ListNode list3 = target;
// 每次迭代,list1 或是 list2都会像后推移一位,直到一方为空。
// 迭代过程中,比较list1和list2节点值,取小的作为list3的下一节点。
// 假设list1长度为m,list2长度为n,那么最多迭代n+m次,时间复杂度O(m+n)。
while (list1 != null && list2 != null) {
if(list1.val <= list2.val) {
list3.next = list1;
list1 = list1.next;
} else {
list3.next = list2;
list2 = list2.next;
}
list3 = list3.next;
}
if (list1 == null) {
list3.next = list2;
}
if (list2 == null) {
list3.next = list1;
}
return target.next;
}
}
递归解法:
我们可以定义一个 merge 操作,用于将两个链表合并。在merge操作中,我们可以将两个链表头部值较小的一个节点与剩下元素的 merge 操作结果合并。
我们直接将以上递归过程建模,同时需要考虑边界情况。
如果 l1 或者 l2 一开始就是空链表 ,那么没有任何操作需要合并,所以我们只需要返回非空链表。否则,我们要判断 l1 和 l2 哪一个链表的头节点的值更小,然后递归地决定下一个添加到结果里的节点。如果两个链表有一个为空,递归结束。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}