Skip to content

Commit

Permalink
2181
Browse files Browse the repository at this point in the history
  • Loading branch information
lzl124631x committed Feb 20, 2022
1 parent dae3372 commit b494e3d
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ The 14 integers less than or equal to 30 whose digit sums are even are
## Solution 1. Brute Force

```cpp
// OJ: https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/
// OJ: https://leetcode.com/problems/count-integers-with-even-digit-sum/
// Author: github.com/lzl124631x
// Time: O(NlgN)
// Space: O(1)
Expand Down
72 changes: 71 additions & 1 deletion leetcode/2181. Merge Nodes in Between Zeros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,74 @@ public:
return dummy.next;
}
};
```
```
## Solution 2.
If we are asked to do it in-place.
```cpp
// OJ: https://leetcode.com/problems/merge-nodes-in-between-zeros/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1) as it's done in-place
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode dummy, *tail = &dummy;
while (head) {
if (head->val == 0) head = head->next;
if (!head) break;
auto node = head;
head = head->next;
while (head->val != 0) {
node->val += head->val;
head = head->next;
}
tail->next = node;
tail = tail->next;
node->next = nullptr;
}
return dummy.next;
}
};
```

If you are asked to add the code to free node:

```cpp
// OJ: https://leetcode.com/problems/merge-nodes-in-between-zeros/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1) as it's done in-place
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode dummy, *tail = &dummy;
while (head) {
if (head->val == 0) {
auto p = head;
head = head->next;
delete p;
}
if (!head) break;
auto node = head;
head = head->next;
while (head->val != 0) {
node->val += head->val;
auto p = head;
head = head->next;
delete p;
}
tail->next = node;
tail = tail->next;
node->next = nullptr;
}
return dummy.next;
}
};
```
## Discuss
https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/1784739/

0 comments on commit b494e3d

Please sign in to comment.