1250. Check If It Is a Good Array

ぐ巨炮叔叔 提交于 2019-12-04 14:55:12

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
class Solution {
    public boolean isGoodArray(int[] A) {
        int x = A[0], y;
        for (int a: A) {
            while (a > 0) {
                y = x % a;
                x = a;
                a = y;
            }
        }
        return x == 1;
    }
}

找最大公约数是不是1.

辗转相除法:第二次开始一直用除数除以余数,知道余数为0,当前除数就是最大公约数。

 

 看起来最后返回的是除数,但其实应该是被除数

    public static int gcd(int a, int b){
        int c = a % b;
        while(c > 0){
            c = a % b;
            a = b;
            b = c;
        }
        return a;
    }

因为最后一步把b赋给a了,然后b其实==0.

最后写了种自己能写的方法

class Solution {
    public boolean isGoodArray(int[] nums) {
        int x = nums[0];
        for(int i = 0; i < nums.length; i++){
            x = gcd(x, nums[i]);
        }
        return x == 1;
    }
    public  int gcd(int a, int b){
        int c = a % b;
        while(c > 0){
            c = a % b;
            a = b;
            b = c;
        }
        return a;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!