java - 使用蛮力的其他数字乘积 InterviewCake 答案

标签 java algorithm

我正在尝试使用蛮力来回答这个问题,这样我就可以理解发生了什么:

https://www.interviewcake.com/question/java/product-of-other-numbers

但问题是我不明白为什么我的逻辑不起作用。到目前为止,这是我尝试过的:

public class EveryInteger {

    public static void main(String[] args) {

        int a1[] = {1, 7, 3, 4};
         int a2[] = new int[4];
          for(int i =0; i<a1.length; i++){
            int index = a1[i];
            int sum = 0;

            for(int j =0; j<a1.length; j++){
                if(a1[i]==a1[j]){
                    continue;
                }

                sum = index * a1[j];
                a2[i] = sum;
                System.out.println(a2[i]);
            }
          }
    }

谁能告诉我你是如何使用两个 for 循环解决这个问题的?

最佳答案

这里有几个问题:

// defining an array like this is confusing because the type is not immediately clear, rather use int[] a1 = ...
int a1[] = {1, 7, 3, 4}; 
// a2 should always have the same length as a1, so use a1.length
int a2[] = new int[4];
for(int i =0; i<a1.length; i++){
    // index is a little confusing, since it's not the index but the value at i
    int index = a1[i];
    // sum is also confusing, since you're working with multiplication here
    // Additionally with multiplication involved, initialize that to 1
    int sum = 0;

    for(int j =0; j<a1.length; j++){
        // comparing only j and i would be sufficient here without accessing the array twice
        if(a1[i]==a1[j]){
            continue;
        }

        // Instead of accumulating the product you reassign it every time, effectively deleting the previous value.
        sum = index * a1[j];
        a2[i] = sum;
        System.out.println(a2[i]);
    }
}

解决方案可能如下所示:

int[] input = {1,7,3,4};
int[] output = new int[input.length];

for(int i = 0; i < input.length; i++) {
  // Accumulates the multiplications.
  int acc = 1;
  for(int j = 0; j < input.length; j++) {
    // check, if not at the same index.
    if(j != i) {
      // only then multiply the current number with the accumulator.
      acc *= input[j];
    }
  }
  // finally write the accumulated product to the output array.
  output[i] = acc;
}

System.out.println(Arrays.toString(output));

结果如愿:

[84, 12, 28, 21]

关于java - 使用蛮力的其他数字乘积 InterviewCake 答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40630478/

相关文章:

java - jsvc & Gradle - 没有控制台输出,Gradle 守护进程崩溃

arrays - 如何从 n 个数组中找到公共(public)元素

algorithm - 国家/州/海洋的地理区域数据

c - 什么算法可以在线性时间内对新值和重复值进行排序,而不使用额外的空间?

python - 求傅立叶系数算法

Java编辑现有文件

java - 将 JSON(或对象)添加到 STRING json 数组

java - 为每个Web应用程序(上下文)保存一个存储库是更好还是通过JNDI或类似技术共享一个公共(public)实例更好?

java - 调用方法但没有任何结果

algorithm - 枚举笛卡尔积同时最小化重复