Skip to content

1979. Find Greatest Common Divisor of Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  int findGCD(vector<int>& nums) {
    return __gcd(ranges::min(nums), ranges::max(nums));
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int findGCD(int[] nums) {
    final int mn = Arrays.stream(nums).min().getAsInt();
    final int mx = Arrays.stream(nums).max().getAsInt();
    return gcd(mn, mx);
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
1
2
3
class Solution:
  def findGCD(self, nums: list[int]) -> int:
    return math.gcd(min(nums), max(nums))