持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第26天,点击查看活动详情
题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 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.
*/
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode result = new ListNode();
ListNode temp = result;
while (true) {
if (list1 == null && list2 == null) {
return null;
} else if (list1 == null) {
temp.val = list2.val;
temp.next = list2.next;
return result;
} else if (list2 == null) {
temp.val = list1.val;
temp.next = list1.next;
return result;
} else if (list1.val <= list2.val) {
temp.val = list1.val;
list1 = list1.next;
} else if (list1.val > list2.val) {
temp.val = list2.val;
list2 = list2.next;
}
temp.next = new ListNode();
temp = temp.next;
}
}
}
总结
性能分析
- 执行耗时:0 ms,击败了 100.00% 的 Java 用户
- 内存消耗:41 MB,击败了 14.86% 的 Java 用户
解题二:递归
思路
如果 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;
}
}
}