Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-09-10 09:18:53
https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list
2807. Insert Greateset Common Divisors in Linked List
給一個 linked list 每一個節點都包含一個整數值
在每對相鄰節點之間 插入一個新節點 值為兩數的最大公約數
返回插入後的 linked list
greatest common divisor 是能整除兩個數的最大正整數
Example 1:
Input: head = [18,6,10,3]
Output: [18,6,6,2,10,1,3]
Explanation: gcd(18,6)=6, gcd(6,10)=2, gcd(10,3)=1
https://assets.leetcode.com/uploads/2023/07/18/ex1_copy.png
Example 2:
Input: head = [7]
Output: [7]
Explanation: 沒有相鄰節點 直接返回原本的 head
https://assets.leetcode.com/uploads/2023/07/18/ex2_copy1.png
Constraints:
節點數 [1, 5000]
節點值 1 <= Node.val <= 1000
思路:
照著做就好
Python Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from math import gcd
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) ->
Optional[ListNode]:
curr = head
while curr and curr.next:
next_node = curr.next
curr.next = ListNode(gcd(curr.val, next_node.val), next_node)
curr = next_code
return head
怎麼又是 Linked List 不過現在對 Linked List 比較懂一些了 還可以
作者: JerryChungYC (JerryChung)   2024-09-10 09:20:00
忘記寫Example了
作者: sustainer123 (caster)   2024-09-10 09:20:00
大師
作者: JIWP (JIWP)   2024-09-10 09:25:00
別倦了
作者: DJYOMIYAHINA (通通打死)   2024-09-10 09:33:00
法國我
作者: dont   2024-09-10 11:13:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com