vault backup: 2022-07-18 14:57:32
This commit is contained in:
parent
db7c547265
commit
3916a9ea80
|
@ -1,4 +1,4 @@
|
|||
sh# Leetcode 01-Matrix
|
||||
# Leetcode 01-Matrix
|
||||
|
||||
#### 2022-07-17 03:15
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
---
|
||||
##### Algorithms:
|
||||
#algorithm #two_pointers
|
||||
#algorithm #two_pointers #recursion
|
||||
##### Data structures:
|
||||
#DS #linked_list
|
||||
##### Difficulty:
|
||||
|
@ -61,9 +61,51 @@ Return _the head of the merged linked list_.
|
|||
|
||||
### Thoughts
|
||||
|
||||
#### Two pointers method
|
||||
|
||||
This is a #two_pointers algorithm, I've done similar problems at leetcode's array list.
|
||||
The only thing to watch out for is when there is one list remaining, remember to add the tails.
|
||||
|
||||
#### Recursion
|
||||
|
||||
Very simple for recursion
|
||||
|
||||
##### Base Case:
|
||||
- Both are nullptr -> return nullptr
|
||||
- One is nullptr -> return another
|
||||
|
||||
##### Pseudocode:
|
||||
- Check for base case:
|
||||
- if list1->val > list2->val, list2's next should be the merged result
|
||||
- if list2->val > list1->val, list1's next should be the merged result.
|
||||
|
||||
### Solution
|
||||
Recursion
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
|
||||
// Recursion
|
||||
// Base case, one is empty or both empty
|
||||
if (!list1) {
|
||||
return list2;
|
||||
} else if (!list2) {
|
||||
return list1;
|
||||
}
|
||||
|
||||
if (list1->val > list2->val) {
|
||||
// insert list1 after list2
|
||||
list2->next = mergeTwoLists(list1, list2->next);
|
||||
return list2;
|
||||
} else {
|
||||
list1->next = mergeTwoLists(list1->next, list2);
|
||||
return list1;
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Two pointers
|
||||
```cpp
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
|
|
Loading…
Reference in a new issue