Skip to content

Latest commit

 

History

History

1979.Find Greatest Common Divisor of Array

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

给你一个整数数组 nums ,返回数组中最大数和最小数的 最大公约数

两个数的 最大公约数 是能够被两个数整除的最大正整数。

 

示例 1:

输入:nums = [2,5,6,9,10]
输出:2
解释:
nums 中最小的数是 2
nums 中最大的数是 10
2 和 10 的最大公约数是 2

示例 2:

输入:nums = [7,5,6,8,3]
输出:1
解释:
nums 中最小的数是 3
nums 中最大的数是 8
3 和 8 的最大公约数是 1

示例 3:

输入:nums = [3,3]
输出:3
解释:
nums 中最小的数是 3
nums 中最大的数是 3
3 和 3 的最大公约数是 3

 

提示:

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000

解法

最大公约数算法:

int gcd(int a, int b) {
	return b > 0 ? gcd(b, a % b) : a;
}

Python3

class Solution:
    def findGCD(self, nums: List[int]) -> int:
        return gcd(max(nums), min(nums))

Java

class Solution {
    public int findGCD(int[] nums) {
        int a = 1, b = 1000;
        for (int num : nums) {
            a = Math.max(a, num);
            b = Math.min(b, num);
        }
        return gcd(a, b);
    }

    private int gcd(int a, int b) {
        return b > 0 ? gcd(b, a % b) : a;
    }
}

C++

class Solution {
public:
    int findGCD(vector<int>& nums) {
        int a = 0, b = 1000;
        for (int num : nums)
        {
            a = max(a, num);
            b = min(b, num);
        }
        return gcd(a, b);
    }
};

Go

func findGCD(nums []int) int {
	a, b := 0, 1000
	for _, num := range nums {
		a = max(a, num)
		b = min(b, num)
	}
	return gcd(a, b)
}

func gcd(a, b int) int {
	if b > 0 {
		return gcd(b, a%b)
	}
	return a
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

...