LeetCode 题解工作台
使数组可以被整除的最少删除次数
给你两个正整数数组 nums 和 numsDivide 。你可以从 nums 中删除任意数目的元素。 请你返回使 nums 中 最小 元素可以整除 numsDivide 中所有元素的 最少 删除次数。如果无法得到这样的元素,返回 -1 。 如果 y % x == 0 ,那么我们说整数 x 整除 y …
5
题型
4
代码语言
3
相关题
当前训练重点
困难 · 数组·数学
答案摘要
如果一个元素能整除数组 `numsDivide` 所有元素,那么这个元素是所有 的最大公约数 的因子。因此,我们可以先求出 `numsDivide` 的最大公约数 。 接下来,将数组 `nums` 排序,然后从头到尾遍历数组 `nums`,找到第一个是最大公约数 的因子的元素,返回当前元素下标即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你两个正整数数组 nums 和 numsDivide 。你可以从 nums 中删除任意数目的元素。
请你返回使 nums 中 最小 元素可以整除 numsDivide 中所有元素的 最少 删除次数。如果无法得到这样的元素,返回 -1 。
如果 y % x == 0 ,那么我们说整数 x 整除 y 。
示例 1:
输入:nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15] 输出:2 解释: [2,3,2,4,3] 中最小元素是 2 ,它无法整除 numsDivide 中所有元素。 我们从 nums 中删除 2 个大小为 2 的元素,得到 nums = [3,4,3] 。 [3,4,3] 中最小元素为 3 ,它可以整除 numsDivide 中所有元素。 可以证明 2 是最少删除次数。
示例 2:
输入:nums = [4,3,6], numsDivide = [8,2,6,10] 输出:-1 解释: 我们想 nums 中的最小元素可以整除 numsDivide 中的所有元素。 没有任何办法可以达到这一目的。
提示:
1 <= nums.length, numsDivide.length <= 1051 <= nums[i], numsDivide[i] <= 109
解题思路
方法一:数学 + 排序
如果一个元素能整除数组 numsDivide 所有元素,那么这个元素是所有 的最大公约数 的因子。因此,我们可以先求出 numsDivide 的最大公约数 。
接下来,将数组 nums 排序,然后从头到尾遍历数组 nums,找到第一个是最大公约数 的因子的元素,返回当前元素下标即可。
时间复杂度 ,其中 和 分别是数组 nums 和 numsDivide 的长度,而 是数组 numsDivide 中的最大值。
实际上,我们也可以不用排序数组 nums,而是直接遍历数组 nums,找到最小的能整除 的元素,然后我们再遍历一次数组 nums,统计小于等于这个元素的元素个数即可。
时间复杂度 。
class Solution:
def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:
x = numsDivide[0]
for v in numsDivide[1:]:
x = gcd(x, v)
nums.sort()
for i, v in enumerate(nums):
if x % v == 0:
return i
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands how divisibility works and can relate array sorting to divisibility checks.
- question_mark
Candidate efficiently handles large arrays and large numbers with mathematical optimization techniques.
- question_mark
Candidate applies a strategic approach to array deletions and can justify the number of deletions required for valid solutions.
常见陷阱
外企场景- error
Failing to realize that sorting nums is essential for checking the smallest divisibility candidate first.
- error
Ignoring the potential to optimize by calculating the GCD of numsDivide before starting the divisibility checks.
- error
Overcomplicating the approach by trying unnecessary operations, such as brute force element deletion or not leveraging sorting.
进阶变体
外企场景- arrow_right_alt
Instead of deleting elements to make the smallest divisor work, try solving the problem by keeping track of the largest divisor of numsDivide.
- arrow_right_alt
Implement a dynamic programming approach where you progressively delete elements and check for divisibility at each step.
- arrow_right_alt
Change the problem's condition by asking for the maximum number that divides all elements of numsDivide instead of the smallest.