Skip to content

Latest commit

 

History

History
142 lines (111 loc) · 2.63 KB

File metadata and controls

142 lines (111 loc) · 2.63 KB

中文文档

Description

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

Solutions

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
}

...