Re: [閒聊] 每日leetcode

看板Marginalman作者 (caster )時間1年前 (2024/09/10 11:54), 編輯推噓2(201)
留言3則, 3人參與, 1年前最新討論串835/1548 (看更多)
※ 引述《dont (dont)》之銘言: : 2807. Insert Greatest Common Divisors in Linked List : ## 思路 : 照著做 中間塞gcd : ## Code : ```python : class Solution: : def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> : Optional[ListNode]: : def get_gcd(x, y): : while y: : x, y = y, x % y : return x : curr = head : while curr and curr.next: : gcd = get_gcd(curr.val, curr.next.val) : curr.next = node = ListNode(gcd, curr.next) : curr = node.next : return head : ``` : 817. Linked List Components : ## 思路 : 先把nums轉成set再掃LinkedList : 如果node在nums裡就res+1並且跳過相連且在nums裡的node : ## Code : ```python : class Solution: : def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int: : nums = set(nums) : res = 0 : while head: : if head.val in nums: : res += 1 : while head and head.val in nums: : head = head.next : else: : head = head.next : return res : ``` 思路: 照著做 Python Code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]: tmp = ListNode(next = head) pre = head head = head.next while head: x = math.gcd(head.val,pre.val) pre.next = ListNode(x, next = head) pre = head head = head.next return tmp.next -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.250.109.31 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725940480.A.6EB.html

09/10 11:55, 1年前 , 1F
剩我不會了
09/10 11:55, 1F

09/10 11:57, 1年前 , 2F
我好佩服你
09/10 11:57, 2F

09/10 11:57, 1年前 , 3F
我直接math 我好爛
09/10 11:57, 3F
文章代碼(AID): #1ctyC0Rh (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ctyC0Rh (Marginalman)