vault backup: 2022-07-18 14:57:32

This commit is contained in:
Juan 2022-07-18 14:57:32 +08:00
parent db7c547265
commit 3916a9ea80
2 changed files with 44 additions and 2 deletions

View file

@ -1,4 +1,4 @@
sh# Leetcode 01-Matrix # Leetcode 01-Matrix
#### 2022-07-17 03:15 #### 2022-07-17 03:15

View file

@ -4,7 +4,7 @@
--- ---
##### Algorithms: ##### Algorithms:
#algorithm #two_pointers #algorithm #two_pointers #recursion
##### Data structures: ##### Data structures:
#DS #linked_list #DS #linked_list
##### Difficulty: ##### Difficulty:
@ -61,9 +61,51 @@ Return _the head of the merged linked list_.
### Thoughts ### Thoughts
#### Two pointers method
This is a #two_pointers algorithm, I've done similar problems at leetcode's array list. 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. 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 ### 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 ```cpp
/** /**
* Definition for singly-linked list. * Definition for singly-linked list.