『Leetcode 5250』检查「好数组」

『题目』:

 给你一个正整数数组 nums,你需要从中任选一些子集,然后将子集中每一个数乘以一个 任意整数,并求出他们的和。

假如该和结果为 1,那么原数组就是一个「好数组」,则返回 True;否则请返回 False

『限制条件』:

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

『输入输出』

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

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

输入:nums = [3,6]
输出:false

『题解』:

裴蜀定理:设a1,a2,a3......ann个整数,d是它们的最大公约数,那么存在整数x1......xn使得x1*a1+x2*a2+...xn*an=d。所以只要枚举每一个数组的元素弄gcd即可。如果最后的d=1就是有解。

『实现』:

public class test1 {

    public int gcd(int a,int b)
    {
        if(b == 0)
        {
            return a;
        }
        return  gcd(b,a%b);
    }

    public boolean isGoodArray(int[] nums) {

        if(nums == null || nums.length == 0) return false;

        int d = nums[0];

        for(int i = 1;i < nums.length;i++)
        {
            d = gcd(d,nums[i]);
        }
        //System.out.println(d);
        if(d == 1) return true;
        return false;
    }

    public static void main(String[] args) {

        test1 of = new test1();
        int[] nums = {12,5,7,23};
        System.out.println(of.isGoodArray(nums));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值