[LeetCode] 1250. Check If It Is a Good Array 检查好数组


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.

Example 1:

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

Example 2:

Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1

Example 3:

Input: nums = [3,6]
Output: false

Constraints:

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

这道题给了一个正整数的数组 nums,定义了一种好数组,说是随便从数组中选几个数字,若可以通过乘以整数相加后得到1,则就是好数组,问给定的数组是否是好数组。这道题是一道 Hard 题目,而且是那种基于数学理论的题目,基本上就是若你没有听说过某个定理,那么基本上就是无法解出这道题目的。这道题考查的是贝祖等式,可以参见永乐老师的讲解视频,说的是对于任何整数 a, b 和 m 的方程 ax + by = m 有整数解的充要条件是m是a和b的最大公约数的倍数。这道题由于m是1,所以最大公约数必须是1。所以只要找到任意两个数字的最大公约数是1即可,也就是可以找整个数组的最大公约数(因为整个数组的最大公约数不会大于任意两个数字的最大公约数),明白了上面这些后,这道题就用几行就可以搞定了,参见代码如下:


class Solution {
public:
    bool isGoodArray(vector<int>& nums) {
        int res = nums[0];
        for (int num : nums) {
            res = gcd(res, num);
            if (res == 1) return true;
        }
        return false;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1250


参考资料:

https://leetcode.com/problems/check-if-it-is-a-good-array/

https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/1071677/Simple-C%2B%2B-with-Explanation

https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/419368/JavaC%2B%2BPython-Chinese-Remainder-Theorem


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2021-11-08 12:33  Grandyang  阅读(433)  评论(0编辑  收藏  举报
Fork me on GitHub