✅【每日一LeetCode】2807. 在链表中插入最大公约数

73 阅读1分钟

image.png

image.png

Python3

方法: 模拟 O(nlogU)O(1)\lgroup O(n \log U)、O(1)\rgroup

# 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]:
        if head.next is None:
            return head

        pre = head
        cur = head.next 
        while cur:
            temp = ListNode(math.gcd(pre.val, cur.val))
            pre.next = temp 
            temp.next = cur 
            pre = cur
            cur = cur.next 
        return head

image.png

# 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]:
        cur = head
        while cur.next:
            cur.next = ListNode(math.gcd(cur.val, cur.next.val), cur.next)
            cur = cur.next.next 

        return head

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertGreatestCommonDivisors(ListNode* head) {
        ListNode* cur = head;
        while (cur->next){
            cur->next = new ListNode(__gcd(cur->val, cur->next->val), cur->next);
            cur = cur->next->next;
        }
        return head;        
    }
};