首页 > 其他 > 详细

1250. Check If It Is a Good Array

时间:2019-11-16 09:43:06      阅读:84      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

1250. Check If It Is a Good Array

原文:https://www.cnblogs.com/wentiliangkaihua/p/11870419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!