LeetCode 题解工作台

找出数组的最大公约数

给你一个整数数组 nums ,返回数组中最大数和最小数的 最大公约数 。 两个数的 最大公约数 是能够被两个数整除的最大正整数。 示例 1: 输入: nums = [2,5,6,9,10] 输出: 2 解释: nums 中最小的数是 2 nums 中最大的数是 10 2 和 10 的最大公约数是 2…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们根据题意模拟即可,即先找出数组 中的最大值和最小值,然后求最大值和最小值的最大公约数。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,返回数组中最大数和最小数的 最大公约数

两个数的 最大公约数 是能够被两个数整除的最大正整数。

 

示例 1:

输入:nums = [2,5,6,9,10]
输出:2
解释:
nums 中最小的数是 2
nums 中最大的数是 10
2 和 10 的最大公约数是 2

示例 2:

输入:nums = [7,5,6,8,3]
输出:1
解释:
nums 中最小的数是 3
nums 中最大的数是 8
3 和 8 的最大公约数是 1

示例 3:

输入:nums = [3,3]
输出:3
解释:
nums 中最小的数是 3
nums 中最大的数是 3
3 和 3 的最大公约数是 3

 

提示:

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
lightbulb

解题思路

方法一:模拟

我们根据题意模拟即可,即先找出数组 nums\textit{nums} 中的最大值和最小值,然后求最大值和最小值的最大公约数。

时间复杂度 O(n)O(n),其中 nn 为数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def findGCD(self, nums: List[int]) -> int:
        return gcd(max(nums), min(nums))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an efficient approach to find the min and max values in one iteration.

  • question_mark

    Ensure that the candidate uses an efficient method like the Euclidean algorithm for GCD.

  • question_mark

    Watch for edge cases such as arrays with identical elements, where GCD is the element itself.

warning

常见陷阱

外企场景
  • error

    Misunderstanding that the problem only asks for the GCD of the smallest and largest numbers, not all pairs.

  • error

    Not handling arrays with identical elements correctly, where the GCD should be the element itself.

  • error

    Using an inefficient method to find the minimum and maximum values, causing unnecessary time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the GCD of the largest two elements instead of min and max.

  • arrow_right_alt

    Calculate the GCD for multiple pairs within the array and return the smallest GCD.

  • arrow_right_alt

    Allow larger arrays, potentially introducing more optimization techniques for finding the min and max.

help

常见问题

外企场景

找出数组的最大公约数题解:数组·数学 | LeetCode #1979 简单