網頁

2025年9月16日 星期二

C C++ GCD LCM解Leetcode難題2197 Replace Non Coprime Numbers in Array[含Py3 code]


C C++ GCD LCM解Leetcode難題2197  Replace Non Coprime Numbers in Array
用binary Euclidean algorithm定義gcd,然後定義lcm之後就是用stack
[Py3 code請進]

-----
Use the binary Euclidean algorithm to define GCD, then define LCM and then use a stack.
class Solution:
    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:
        top=-1
        for x in nums:
            cur=x
            while top!=-1:
                g=gcd(nums[top], cur)
                if g==1: break
                cur=nums[top]//g*cur
                top-=1
            top+=1
            nums[top]=cur
        return nums[:top+1]
        

沒有留言:

張貼留言

HTML 編輯器