一、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
方法一:裴蜀定理
对于方程式
只有满足 a、b 的最大公约数可以被 c 整除时
方程才有整数解,比如当方程式:
6 和 8 的 gcd 为 2,2 可以被 10 整除,所以方程式有整数解,且整数解 x、y 的有很多,比如:
Q:那如何判断是否是好数组呢?
答:假设子集为 ,那么要满足
则需要满足:
所以我们只需要从左到右求每个数的 gcd 然后判断是否满足: 即可
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;
}
}
复杂度分析
- 时间复杂度:,
- 空间复杂度:,