LeetCode 1250. Check "good array" (set / greatest common divisor)

Article Directory

1. Title

Give you an array of positive integers nums, you need to choose some subsets from it , then multiply each number in the subset by an arbitrary integer, and find their sum.

If the result of the sum is 1, then the original array is a "good array", return True; otherwise, return False.

示例 1:
输入:nums = [12,5,7,23]
输出:true
解释:挑选数字 575*3 + 7*(-2) = 1

示例 2:
输入:nums = [29,6,10]
输出:true
解释:挑选数字 29, 61029*1 + 6*(-3) + 10*(-1) = 1

示例 3:
输入:nums = [3,6]
输出:false
 
提示:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-if-it-is-a-good-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. Problem solving

  • Insert numbers into set, traverse backward
  • The current number is modulo the previous number, modulo == 1, return true
  • mold! = 1, insert the die into the set
class Solution {
    
    
public:
    bool isGoodArray(vector<int>& nums) {
    
    
        set<int> s(nums.begin(), nums.end());
        if(*s.begin()==1) return true;
        auto it = s.rbegin();
        int prev = *it, mod;
        for(it++; it != s.rend(); ++it)
        {
    
    
            if(*it == 0)
                break;
            mod = prev%*it;
            if(mod == 1)
                return true;
            else
                s.insert(mod);
            prev = *it;
        }
        return false;
    }
};

436 ms 44 MB

Look at the answer again: Pei Shu theorem

  • Find the greatest common divisor of all numbers, it needs to be 1
class Solution {
    
    
public:
    bool isGoodArray(vector<int>& nums) {
    
    
        int g = nums[0];
        for(int i = 1; i < nums.size(); ++i)
        {
    
    
            g = __gcd(g, nums[i]);
        }
        return g == 1;
    }
};
class Solution {
    
    
public:
    bool isGoodArray(vector<int>& nums) {
    
    
        int g = nums[0];
        for(int i = 1; i < nums.size(); ++i)
        {
    
    
            g = gcd(g, nums[i]);
        }
        return g == 1;
    }
    int gcd(int a, int b)
    {
    
    
        int r;
        while(b)
        {
    
    
            r = a%b;
            a = b;
            b = r;
        }
        return a;
    }
};

My CSDN blog address https://michael.blog.csdn.net/

Long press or scan the code to follow my official account (Michael Amin), cheer together, learn and progress together!
Michael Amin

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/108960785