LeetCode 2197. 替换数组中的非互质数

2197. 替换数组中的非互质数

给你一个整数数组 nums 。请你对数组执行下述操作:

  1. 从 nums 中找出 任意 两个 相邻 的 非互质 数。
  2. 如果不存在这样的数,终止 这一过程。
  3. 否则,删除这两个数,并 替换 为它们的 最小公倍数(Least Common Multiple,LCM)。
  4. 只要还能找出两个相邻的非互质数就继续 重复 这一过程。

返回修改后得到的 最终 数组。可以证明的是,以 任意 顺序替换相邻的非互质数都可以得到相同的结果。

生成的测试用例可以保证最终数组中的值 小于或者等于 108 。

两个数字 x 和 y 满足 非互质数 的条件是:GCD(x, y) > 1 ,其中 GCD(x, y) 是 x 和 y 的 最大公约数 。

示例 1 :

输入:nums = [6,4,3,2,7,6,2]
输出:[12,7,6]
解释:
- (6, 4) 是一组非互质数,且 LCM(6, 4) = 12 。得到 nums = [12,3,2,7,6,2] 。
- (12, 3) 是一组非互质数,且 LCM(12, 3) = 12 。得到 nums = [12,2,7,6,2] 。
- (12, 2) 是一组非互质数,且 LCM(12, 2) = 12 。得到 nums = [12,7,6,2] 。
- (6, 2) 是一组非互质数,且 LCM(6, 2) = 6 。得到 nums = [12,7,6] 。
现在,nums 中不存在相邻的非互质数。
因此,修改后得到的最终数组是 [12,7,6] 。
注意,存在其他方法可以获得相同的最终数组。

示例 2 :

输入:nums = [2,2,1,1,3,3,3]
输出:[2,1,1,3]
解释:
- (3, 3) 是一组非互质数,且 LCM(3, 3) = 3 。得到 nums = [2,2,1,1,3,3] 。
- (3, 3) 是一组非互质数,且 LCM(3, 3) = 3 。得到 nums = [2,2,1,1,3] 。
- (2, 2) 是一组非互质数,且 LCM(2, 2) = 2 。得到 nums = [2,1,1,3] 。
现在,nums 中不存在相邻的非互质数。 
因此,修改后得到的最终数组是 [2,1,1,3] 。 
注意,存在其他方法可以获得相同的最终数组。

提示:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5
  • 生成的测试用例可以保证最终数组中的值 小于或者等于 10^8 。

提示 1

Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible.


提示 2

If a new value is formed, we should recursively check if it can be merged with the value to its left.


提示 3

To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left).

解法1:栈

由于题目给出了「任意顺序替换相邻的非互质数都可以得到相同的结果」,因此我们可以从前往后进行替换。

我们可以使用一个栈来进行替换操作。具体地,我们对数组 nums 进行一次遍历。当遍历到 nums[i] 时。在其被放入栈顶前,我们重复进行替换操作,直到 nums[i] 和栈顶的元素互质,或者栈为空为止。此时,我们再将替换完成的 nums[i] 放入栈顶。

最终栈底到栈顶的元素序列即为答案。

Java版:

class Solution {
    public List<Integer> replaceNonCoprimes(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int num : nums) {
            while (!stack.isEmpty() && gcd(num, stack.peek()) > 1) {
                num = lcm(num, stack.pop());
            } 
            stack.push(num);
        }
        List<Integer> list = stack.stream().collect(Collectors.toList());
        Collections.reverse(list);
        return list;
    }

    public int gcd(int a, int b) {
        if (a < b) {
            gcd(b, a);
        }
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public int lcm(int a, int b) {
        if (a < b) {
            lcm(b, a);
        }
        int n = gcd(a, b);
        return a / n * b;
    }
}

另一种写法:

class Solution {
    public List<Integer> replaceNonCoprimes(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int num : nums) {
            while (!stack.isEmpty() && gcd(num, stack.peek()) > 1) {
                num = lcm(num, stack.pop());
            } 
            stack.push(num);
        }
        List<Integer> list = new ArrayList<>(stack.size());
        while (!stack.isEmpty()) {
            list.add(stack.pollLast());
        }
        return list;
    }

    public int gcd(int a, int b) {
        if (a < b) {
            gcd(b, a);
        }
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public int lcm(int a, int b) {
        if (a < b) {
            lcm(b, a);
        }
        int n = gcd(a, b);
        return a / n * b;
    }
}

 

Python3版:

class Solution:
    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:
        stack = []
        for num in nums:
            while stack and math.gcd(stack[-1], num) > 1:
                num = math.lcm(stack[-1], num)
                stack.pop()
            stack.append(num)
        return stack

自己写 gcd 和 lcm:

class Solution:
    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:
        def gcd(a, b):
            if a < b:
                gcd(b, a)
            if b == 0:
                return a
            return gcd(b, a % b)
        
        def lcm(a, b):
            if a < b:
                lcm(b, a)
            n = gcd(a, b)
            return a / n * b
        
        stack = []
        for num in nums:
            while stack and gcd(stack[-1], num) > 1:
                num = math.lcm(stack[-1], num)
                stack.pop()
            stack.append(num)
        return stack

 

复杂度分析

  • 时间复杂度:O(nlogC),其中 n 是数组 nums 的长度,C 是数组 nums 中的数据范围,O(logC) 即为单次计算最大公约数需要的时间。
  • 空间复杂度:O(1)。这里不计入返回值需要使用的空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值