[LeetCode] 1979. Find Greatest Common Divisor of Array

Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.

Example 2:
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.

Example 3:
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.

Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000

找出数组的最大公约数。

思路

与其他求最大公约数的题目类似。

复杂度

时间O(n) - 需要用O(n)的时间找到最大的数字和最小的数字,然后再去求二者的最大公约数。
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int findGCD(int[] nums) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int num : nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
return helper(min, max);
}

private int helper(int a, int b) {
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
if (a == b) {
return a;
}
return helper(b, a % b);
}
}

[LeetCode] 1979. Find Greatest Common Divisor of Array
https://shurui91.github.io/posts/3832381755.html
Author
Aaron Liu
Posted on
January 6, 2024
Licensed under