题目链接:1979. 找出数组的最大公约数
题目要求的是数组中最大值与最小值的最大公约数。这里先对数组排序,取首尾两个元素,再计算它们的 gcd。
Python 代码如下:
import math
class Solution:
def findGCD(self, nums: List[int]) -> int:
nums.sort()
return math.gcd(nums[0], nums[-1])Python 的 math 模块提供 gcd 函数,可以直接计算最大公约数。
C++ 代码如下:
class Solution {
public:
int findGCD(vector<int>& nums) {
sort(nums.begin(), nums.end());
return __gcd(nums[0], nums[nums.size() - 1]);
}
};这份 C++ 写法通过 algorithm 头文件中的 __gcd 函数计算最大公约数。
谢谢你读到这里。 ✧