首页 > 解决方案 > “两组之间”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;

}

我的代码没有给出正确的解决方案,我不明白为什么。

标签: javaalgorithm

解决方案


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;
}

进步很大。你非常亲近。算法准确且高效。

只有一个错误:您正在重置变量xy条件if

如果条件不成立怎么办?然后变量永远不会重置,所有未来的计算都是在 和 中的那些错误值上完成xy


喜欢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();

推荐阅读