Re: [閒聊] 每日leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
tmp := head
for head.Next != nil {
newnode := &ListNode{gcd(head.Val, head.Next.Val), head.Next}
head.Next = newnode
head = head.Next.Next
}
return tmp
}
func gcd(a, b int) int {
if a%b == 0 {
return b
}
return gcd(b, a%b)
}2807. Insert Greatest Common Divisors in Linked List
給一個linked list的head
在兩個node之間插入一個node
這個node的value是那兩個node的最大公因數
思路:
沒什麼好講的就照做
然後a跟b的最大公因數(n)就
n= a%b==0 ? b : gcd(a,b)
就這樣
golang code :
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.178.79 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725975109.A.AC1.html
討論串 (同標題文章)
完整討論串 (本文為第 838 之 1548 篇):