[栈模拟]2197. 替换数组中的非互质数
2197. 替换数组中的非互质数
两数的乘积 = 最大公约数 × 最小公倍数https://blog.csdn.net/m0_46322965/article/details/151766720?spm=1001.2014.3001.5501由于 LCM 本质是质因数分解中质数的指数取最大值
对于任意一种合并顺序,我们总是可以将该顺序重排成:
- 优先选择最左边的能合并的相邻元素,将其合并。
这可以用栈模拟:
- 创建一个空栈。
- 从左到右遍历 nums。
- 设 x=nums[i]。如果栈不为空且 x 与栈顶不互质,那么弹出栈顶 y,更新 x 为 LCM(x,y)。循环直到栈为空或者 x 与栈顶互质。
- 把 x 入栈。
- 遍历结束,栈即为答案。
class Solution:def replaceNonCoprimes(self, nums: List[int]) -> List[int]:st = []for i in nums:while st and gcd(i,st[-1]) > 1:i = lcm(i,st.pop())st.append(i)return st