21. Merge Two Sorted Lists

Leetcode

https://leetcode.com/problems/merge-two-sorted-lists/arrow-up-right

題目

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

解答

  • 方法一

Runtime: 113 ms, faster than 39.65% of JavaScript online submissions for Merge Two Sorted Lists.

Memory Usage: 44.3 MB, less than 5.02% of JavaScript online submissions for Merge Two Sorted Lists.

  • 方法二

Recursion

Runtime: 145 ms, faster than 14.29% of JavaScript online submissions for Merge Two Sorted Lists.

Memory Usage: 43.9 MB, less than 6.58% of JavaScript online submissions for Merge Two Sorted Lists.

  • 方法三

創建一個 dummy node 改良方法一

Runtime: 117 ms, faster than 37.19% of JavaScript online submissions for Merge Two Sorted Lists.

Memory Usage: 44 MB, less than 5.97% of JavaScript online submissions for Merge Two Sorted Lists.

Time complexity : O(n+m)

Space complexity : O(1)

Last updated