carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1979: Find Greatest Common Divisor of Array #316

Open carloscn opened 1 year ago

carloscn commented 1 year ago

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

carloscn commented 1 year ago

Analysis

求两个数的最大公约数,可以使用更相减损法

思路:

1、如果a > b a = a - b; 2、如果b > a b = b - a; 3、假如a = b,则 a或 b是最大公约数; 4、如果a != b;则继续从一开始执行; 5、也就是说循环的判断条件为a != b,直到a = b时,循环结束。

举例说明:

a = 28 b = 21
a>b

则 a = a - b = 28 - 21 = 7
         b = 21    
b>a

则 b = b-a = 21 - 7 = 14
          a = 7
b>a

则 b = b - a = 14 - 7 = 7
         a = 7
此时 a = b =7
循环结束
pub fn find_gcd(nums: Vec<i32>) -> i32
{
    if nums.len() < 1 {
        return 0;
    }

    let mut max_val:i32 = i32::MIN;
    let mut min_val:i32 = i32::MAX;

    for i in 0..nums.len() {
        max_val = max_val.max(nums[i]);
        min_val = min_val.min(nums[i]);
    }

    while max_val != min_val {
        if max_val > min_val {
            max_val -= min_val;
        }
        if max_val < min_val {
            min_val -= max_val;
        }
    }

    return max_val;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168088 https://github.com/carloscn/structstudy/commit/e15c1329a9e99918a24a33436727b58d9f4f1c93