Re: [閒聊] 每日leetcode

作者: sustainer123 (caster)   2024-07-04 09:31:49
https://leetcode.com/problems/merge-nodes-in-between-zeros
2181. Merge Nodes in Between Zeros
給定一linked list head 請合併0-0之間的節點 此節點的值為合併節點之總和
修改後的linked list不可包含0
Example 1:
Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
Example 2:
Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
Constraints:
The number of nodes in the list is in the range [3, 2 * 105].
0 <= Node.val <= 1000
There are no two consecutive nodes with Node.val == 0.
The beginning and end of the linked list have Node.val == 0.
思路:
蝦雞巴寫 我幾百年沒碰linked list 對啊
大概就遇到0 創新node 沒有就加總
Python Code:
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
total = 0
result = ListNode()
tmp = result
head = head.next
while head:
if head.val == 0:
tmp.next = ListNode(total)
tmp = tmp.next
total = 0
else:
total += head.val
head = head.next
return result.next
作者: Furina (芙寧娜)   2024-07-04 09:32:00
大師
作者: DJYOMIYAHINA (通通打死)   2024-07-04 10:25:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com