使数组可以被整除的最少删除次数
难度:
标签:
题目描述
代码结果
运行时间: 56 ms, 内存: 27.0 MB
/*
思路:
1. 使用 Java Stream API 计算 numsDivide 的最大公约数 gcd。
2. 过滤 nums 数组,找到第一个能整除 gcd 的元素。
3. 返回找到元素的索引或 -1。
*/
import java.util.Arrays;
public class Solution {
public int minDeletions(int[] nums, int[] numsDivide) {
// 计算 numsDivide 的最大公约数
int gcd = Arrays.stream(numsDivide).reduce(this::gcd).getAsInt();
// 排序 nums
Arrays.sort(nums);
// 找到第一个能整除 gcd 的元素
return Arrays.stream(nums)
.filter(num -> gcd % num == 0)
.findFirst()
.map(num -> findIndex(nums, num))
.orElse(-1);
}
// 计算两个数的最大公约数
private int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
// 查找 num 在数组中的索引
private int findIndex(int[] nums, int num) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num) return i;
}
return -1;
}
}
解释
方法:
本题解首先通过计算 numsDivide 中所有元素的最大公约数(GCD)x,从而确定需要的整除因子。然后在 nums 中查找可以被 x 整除的最小元素 y。如果找到这样的 y,则计算必须删除 nums 中所有小于 y 的元素才能使 y 成为 nums 中的最小元素。如果没有找到可以整除 x 的元素,则返回 -1。
时间复杂度:
O(n + k)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么首先计算 `numsDivide` 中所有元素的最大公约数(GCD)?这个操作在算法中起到了什么关键作用?
▷🦆
题解中提到找到可以被 GCD 整除的 `nums` 中的最小元素,为什么选择最小元素作为目标?
▷🦆
在题解中,如果 `nums` 中不存在可以被 GCD 整除的元素,直接返回 `-1`。这种情况是否意味着 `numsDivide` 的 GCD 太大,或者 `nums` 的元素范围不够广?
▷🦆
题解中使用了 `min((v for v in nums if x % v == 0), default=0)` 来寻找符合条件的最小元素,请解释 `default=0` 在这里的具体作用是什么?
▷