將兩個升序鏈表合并為一個新的 升序 鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
https://leetcode-cn.com/problems/merge-two-sorted-lists/
示例1:
image輸入: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 <= 100
l1 和 l2 均按 非遞減順序 排列
Java解法
思路:
- 合并有序鏈表是基本操作,其他問題中的步驟會用到這一步,中間只涉及到鏈接的切斷、連接
- 考慮結點比較+遞歸方法完成操作
package sj.shimmer.algorithm;
/**
* Created by SJ on 2021/2/7.
*/
class D14 {
public static void main(String[] args) {
System.out.println(mergeTwoLists(ListNode.createNode(new int[]{1,2,4}),ListNode.createNode(new int[]{1,3,4})));
System.out.println(mergeTwoLists(ListNode.createNode(new int[]{}),ListNode.createNode(new int[]{})));
System.out.println(mergeTwoLists(ListNode.createNode(new int[]{}),ListNode.createNode(new int[]{0})));
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null&&l2 == null) {
return null;
}
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = null;
if (l1.val>l2.val) {
head = l2;
head.next = mergeTwoLists(l1,l2.next);
}else {
head = l1;
head.next = mergeTwoLists(l1.next,l2);
}
return head;
}
}
image
官方解
-
遞歸
思路一樣,不過好像 又是優雅。。。
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; } } }
- 時間復雜度:O(n+m)
- 空間復雜度:O(n+m)
-
迭代
- 聲明一個假的頭結點用于記錄要返回的頭結點,再聲明一個指針結點,記錄每次比較的結果及下一次比較的位置
- 比較結點,結果作為指針結點的next,指針后移,直到完成比較
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode prehead = new ListNode(-1); ListNode prev = prehead; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { prev.next = l1; l1 = l1.next; } else { prev.next = l2; l2 = l2.next; } prev = prev.next; } // 合并后 l1 和 l2 最多只有一個還未被合并完,我們直接將鏈表末尾指向未合并完的鏈表即可 prev.next = l1 == null ? l2 : l1; return prehead.next; } }
優勢,占用空間少,同時時間上也不會拉長
- 時間復雜度:O(n+m)
- 空間復雜度:O(1),只需要幾個結點的位置來記錄,不像遞歸涉及到多個方法的嵌套,存儲空間拉長