Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-09-10 21:31:46
/**
* 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 :

Links booklink

Contact Us: admin [ a t ] ucptt.com