Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/09/10 09:18), 1年前編輯推噓3(302)
留言5則, 5人參與, 1年前最新討論串833/1548 (看更多)
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 比較懂一些了 還可以 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.52.67 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725931135.A.C19.html

09/10 09:20, 1年前 , 1F
忘記寫Example了
09/10 09:20, 1F
※ 編輯: JerryChungYC (60.251.52.67 臺灣), 09/10/2024 09:24:58

09/10 09:20, 1年前 , 2F
大師
09/10 09:20, 2F

09/10 09:25, 1年前 , 3F
別倦了
09/10 09:25, 3F
※ 編輯: JerryChungYC (60.251.52.67 臺灣), 09/10/2024 09:25:50

09/10 09:33, 1年前 , 4F
法國我
09/10 09:33, 4F

09/10 11:13, 1年前 , 5F
大師
09/10 11:13, 5F
文章代碼(AID): #1ctvv_mP (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ctvv_mP (Marginalman)