Skip to content

Commit 1a74c9d

Browse files
committed
add 21 merge linked list
1 parent e50fc0f commit 1a74c9d

File tree

2 files changed

+84
-1
lines changed

2 files changed

+84
-1
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
layout: leetcode
3+
title: "21. Merge Two Sorted Lists"
4+
categories: [leetcode]
5+
---
6+
7+
[Leetcode Link](https://leetcode.com/problems/merge-two-sorted-lists/)
8+
9+
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
10+
11+
12+
```
13+
Example 1:
14+
15+
16+
Input: l1 = [1,2,4], l2 = [1,3,4]
17+
Output: [1,1,2,3,4,4]
18+
19+
Example 2:
20+
21+
Input: l1 = [], l2 = []
22+
Output: []
23+
24+
Example 3:
25+
26+
Input: l1 = [], l2 = [0]
27+
Output: [0]
28+
29+
30+
Constraints:
31+
32+
The number of nodes in both lists is in the range [0, 50].
33+
-100 <= Node.val <= 100
34+
Both l1 and l2 are sorted in non-decreasing order.
35+
```
36+
37+
# Solution
38+
39+
## Iteration
40+
41+
T: O(m + n), S:O(1)
42+
43+
```python
44+
def mergeTwoLists(self, l1, l2):
45+
prehead = ListNode(-1)
46+
47+
curr = prehead
48+
while l1 and l2:
49+
if l1.val < l2.val:
50+
curr.next = l1
51+
l1 = l1.next
52+
else:
53+
curr.next = l2
54+
l2 = l2.next
55+
curr = curr.next
56+
curr.next = l1 or l2
57+
58+
return prehead.next
59+
```
60+
61+
## Recursion
62+
63+
T: O(m + n), S:O(m + n)
64+
```python
65+
def mergeTwoList(self, l1, l2):
66+
if not l1: return l2
67+
if not l2: return l1
68+
69+
if l1.val < l2.val:
70+
l1.next = self.mergeTwoList(l1.next, l2)
71+
return l1
72+
else:
73+
l2.next = self.mergeTwoList(l1, l2.next)
74+
return l2
75+
```

media/js/tag-search-data.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,15 @@ var problems = {
7171
notes: "hashmap, T: O(N^3), S: O(N)",
7272
templates: [],
7373
},
74-
"22": {
74+
"21": {
75+
name: "21. Merge Two Sorted Lists",
76+
url: "/leetcode/21-merge-two-sorted-lists",
77+
tags: ["sort", "linked_list"],
78+
keywords: ["merge_sort", "lv_1"],
79+
templates: ["merge_sort"],
80+
notes: "Use dummy head",
81+
},
82+
"22": {
7583
name: "22. Generate Parentheses",
7684
url: "/leetcode/22-generate-parentheses",
7785
tags: ["backtrack", "array"],

0 commit comments

Comments
 (0)