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

解法

方法一:模拟

根据题意模拟即可,即先找出数组 nums 中的最大值和最小值,然后求最大值和最小值的最大公约数。

时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 nums 的长度。

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 x : nums) {
            a = Math.max(a, x);
            b = Math.min(b, x);
        }
        return gcd(a, b);
    }

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

C++

class Solution {
public:
    int findGCD(vector<int>& nums) {
        int a = *max_element(nums.begin(), nums.end());
        int b = *min_element(nums.begin(), nums.end());
        return gcd(a, b);
    }
};

Go

func findGCD(nums []int) int {
	a, b := 1, 1000
	for _, x := range nums {
		if a < x {
			a = x
		}
		if b > x {
			b = x
		}
	}
	return gcd(a, b)
}

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

TypeScript

function findGCD(nums: number[]): number {
    let a = 1;
    let b = 1000;
    for (const x of nums) {
        a = Math.max(a, x);
        b = Math.min(b, x);
    }
    return gcd(a, b);
}

function gcd(a: number, b: number): number {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

...