Voyz's Studio.

LeetCode算法笔记--合并两个有序链表

字数统计: 361阅读时长: 1 min
2020/11/30 Share

LeetCode算法笔记–Day34

21. Merge Two Sorted Lists

题目:

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

example
input: 1->2->4, 1->3->4
output: 1->1->2->3->4->4

My Answer:

方法一:递归

  • 时间复杂度:O(n + m)
  • 空间复杂度:O(n + m)

Snip20200730_3.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, 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(1)

  • 当 l1 和 l2 都不是空链表时,判断 l1 和 l2 哪一个链表的头节点的值更小,将较小值的节点添加到结果里,当一个节点被添加到结果里之后,将对应链表中的节点向后移一位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let preHead = new ListNode(-1);
let _pre = preHead;

while(l1 != null && l2 != null){
if(l1.val < l2.val){
_pre.next = l1;
l1 = l1.next;
}else{
_pre.next = l2;
l2 = l2.next;
}
_pre = _pre.next;
}
_pre.next = l1 == null ? l2 : l1;
return preHead.next
};

Snip20200730_2.png

CATALOG
  1. 1. LeetCode算法笔记–Day34
  2. 2. 21. Merge Two Sorted Lists
    1. 2.1. 题目:
    2. 2.2. My Answer:
      1. 2.2.1. 方法一:递归
      2. 2.2.2. 方法二:迭代