java - “两组之间”hackerrank 问题中的问题
问题描述
问题:您将得到两个整数数组,并要求您确定满足以下两个条件的所有整数:
第一个数组的元素是所考虑的整数的所有因数 所考虑的整数是第二个数组的所有元素的因数 这些数字被称为介于两个数组之间。您必须确定存在多少这样的数字。
例如:示例输入
2 3
2 4
16 32 96
样本输出
3
我的代码:
public static int getTotalX(int n, int m, List<Integer> a, List<Integer> b) {
int total=0,x=0,y=0;
for(int i=a.get(n-1);i<=b.get(0);i++)
{
for(int j=0;j<n;j++)
{
//to check if the elements in list 'a' can divide the integer.
if(i%a.get(j)==0)
{
y++;
}
}
//if every element in list a can divide the integer go forward
if(y==n)
{
for(int k=0;k<m;k++)
{
//to check if the elements of list 'b' is divisible by integer
if(b.get(k)%i==0)
{
x++;
}
}
y=0;
//if every element of 'b' is divisible by integer, count how many such integers are there
if(x==m)
{
total++;
x=0;
}
}
}
return total;
}
我的代码没有给出正确的解决方案,我不明白为什么。
解决方案
private static int getTotalX(int n, int m, List<Integer> a, List<Integer> b) {
int total = 0, x = 0, y = 0;
for (int i = a.get(n - 1); i <= b.get(0); i++) {
for (int j = 0; j < n; j++) {
if (i % a.get(j) == 0) {
y++;
}
}
if (y == n) {
for (int k = 0; k < m; k++) {
if (b.get(k) % i == 0) {
x++;
}
}
if (x == m) {
total++;
}
}
// changes here
y = 0;
x = 0;
}
return total;
}
进步很大。你非常亲近。算法准确且高效。
只有一个错误:您正在重置变量x
和y
条件if
。
如果条件不成立怎么办?然后变量永远不会重置,所有未来的计算都是在 和 中的那些错误值上完成x
的y
。
喜欢Java8?这是一个单行:
return (int) IntStream.rangeClosed(a.get(n - 1), b.get(0))
.filter(i -> a.stream().filter(value -> i % value == 0).count() == a.size())
.filter(i -> b.stream().filter(value -> value % i == 0).count() == b.size())
.count();
推荐阅读
- python - 从脚本目录/当前目录运行 Python 脚本
- office-js - `Office.context.mailbox.userProfile.accountType` 误报办公室帐户类型
- javascript - 分析性能——为什么我的 DOM 在事件处理程序被调用之前就被锁定了?
- c++ - new bool** matrix vs new bool*matrix vs new bool matrix 不同类型的 cpp 初始化混淆?
- javascript - 如何异步加载 UIkit 模式的内容?
- css - 如何使用 SASS 在悬停时显示相邻的兄弟姐妹?
- javascript - 拖动并按住鼠标 Codeceptjs Puppeteer
- python - Pandas VariableOffsetWindowIndexer 似乎做了一些超出预期的事情
- html - 如何同时定义具有固定宽度但自动列宽的表格?
- vault - 监控 Hashicorp vaut 字段