1. 程式人生 > 其它 >[LeetCode] 1250. Check If It Is a Good Array 檢查好陣列

[LeetCode] 1250. Check If It Is a Good Array 檢查好陣列


Given an arraynumsofpositive integers. Your task is to select some subset ofnums, multiply each element by an integer and add all these numbers.The array is said to begoodif you can obtain a sum of1from the array by any possible subset and multiplicand.

ReturnTrueif the array isgoodotherwisereturnFalse

.

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 題目講解彙總(持續更新中...)


喜歡請點贊,疼愛請打賞❤️~.~


微信打賞


Venmo 打賞