21.Merge-Two-Sorted-Lists
21. Merge Two Sorted Lists
题目地址
https://www.lintcode.com/problem/merge-two-sorted-lists
https://leetcode.com/problems/merge-two-sorted-lists
题目描述
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.代码
Approach 1: Iteration
Intuition
We can achieve the same idea via iteration by assuming that l1 is entirely less than l2 and processing the elements one-by-one, inserting elements of l2 in the necessary places in l1.
Complexity Analysis
Time complexity : O(n + m)
Space complexity : O(1)
Approach 2: Recursion
Intuition
We can recursively define the result of a merge operation on two lists as the following (avoiding the corner case logic surrounding empty lists):
list1.next = merge(list1.next, list2) list1.val < list2.val
list2.next = merge(list1, list2.next) otherwise
Namely, the smaller of the two lists' heads plus the result of a merge on the rest of the elements.
Complexity Analysis
Time complexity : O(n + m)
Space complexity : O(n + m)
The first call to
mergeTwoListsdoes not return until the ends of bothl1andl2have been reached, so n + m stack frames consume O(n + m)space.
Last updated
Was this helpful?