【数学】A077_LC_检查「好数组」(裴蜀定理)

一、Problem

Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.

Return True if the array is good otherwise return False.

Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9

二、Solution

方法一:裴蜀定理

对于方程式

ax+by=ca,b,cZax + by = c,a,b,c∈Z

只有满足 a、b 的最大公约数可以被 c 整除时 gcd(a,b)  cgcd(a, b)\ |\ c

方程才有整数解,比如当方程式:
6x+8y=106x + 8y = 10

6 和 8 的 gcd 为 2,2 可以被 10 整除,所以方程式有整数解,且整数解 x、y 的有很多,比如:x=1y=2x=5y=5....x=-1,y=2;x = -5,y = 5....

Q:那如何判断是否是好数组呢?

答:假设子集为 a0a2...ain[1na_0,a_2,...,a_i,n∈ [1,n),那么要满足
x1×a1+x2×a2+...+xi×ai=1x_1 × a_1 + x_2 × a_2 + ... +x_i × a_i = 1

则需要满足:
gcd(a1a2...ai)=1gcd(a_1,a_2,...,a_i) = 1

所以我们只需要从左到右求每个数的 gcd 然后判断是否满足:gcd=1gcd = 1 即可

class Solution {
    int gcd(int a, int b) {
        return a == 0 ? b : gcd(b%a, a);
    }
    public boolean isGoodArray(int[] a) {
        int g = a[0];
        for (int i = 1; i < a.length; i++)
            g = gcd(g, a[i]);
        return g == 1;
    }
}

复杂度分析

  • 时间复杂度:O(nlogm)O(nlogm)
  • 空间复杂度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章