【數學】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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章