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 比較懂一些了 還可以 -- ※ 發信站: 批踢踢實業坊(pttweb.org.tw), 來自: 60.251.52.67 (臺灣) ※ 文章網址: https://pttweb.org.tw/Marginalman/M.1725931135.A.C19
JerryChungYC: 忘記寫Example了 09/10 09:20
sustainer123: 大師 09/10 09:20
JIWP: 別倦了 09/10 09:25
DJYOMIYAHINA: 法國我 09/10 09:33