You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2100-2199/2181.Merge Nodes in Between Zeros/README_EN.md
+39-27
Original file line number
Diff line number
Diff line change
@@ -31,7 +31,7 @@ tags:
31
31
<pre>
32
32
<strong>Input:</strong> head = [0,3,1,0,4,5,2,0]
33
33
<strong>Output:</strong> [4,11]
34
-
<strong>Explanation:</strong>
34
+
<strong>Explanation:</strong>
35
35
The above figure represents the given linked list. The modified list contains
36
36
- The sum of the nodes marked in green: 3 + 1 = 4.
37
37
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
@@ -42,7 +42,7 @@ The above figure represents the given linked list. The modified list contains
42
42
<pre>
43
43
<strong>Input:</strong> head = [0,1,0,3,0,2,2,0]
44
44
<strong>Output:</strong> [1,3,4]
45
-
<strong>Explanation:</strong>
45
+
<strong>Explanation:</strong>
46
46
The above figure represents the given linked list. The modified list contains
47
47
- The sum of the nodes marked in green: 1 = 1.
48
48
- The sum of the nodes marked in red: 3 = 3.
@@ -65,7 +65,15 @@ The above figure represents the given linked list. The modified list contains
65
65
66
66
<!-- solution:start -->
67
67
68
-
### Solution 1
68
+
### Solution 1: Simulation
69
+
70
+
We define a dummy head node $\textit{dummy}$, a pointer $\textit{tail}$ pointing to the current node, and a variable $\textit{s}$ to record the sum of the values of the current nodes.
71
+
72
+
Next, we traverse the linked list starting from the second node. If the value of the current node is not 0, we add it to $\textit{s}$. Otherwise, we add $\textit{s}$ to the node after $\textit{tail}$, set $\textit{s}$ to 0, and update $\textit{tail}$ to the next node.
73
+
74
+
Finally, we return the node next to $\textit{dummy}$.
75
+
76
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list.
69
77
70
78
<!-- tabs:start -->
71
79
@@ -83,7 +91,7 @@ class Solution:
83
91
s =0
84
92
cur = head.next
85
93
while cur:
86
-
if cur.val!=0:
94
+
if cur.val:
87
95
s += cur.val
88
96
else:
89
97
tail.next = ListNode(s)
@@ -145,9 +153,9 @@ public:
145
153
ListNode* tail = dummy;
146
154
int s = 0;
147
155
for (ListNode* cur = head->next; cur; cur = cur->next) {
0 commit comments