首页 > 解决方案 > 为什么数组搜索错误对于 case [-2,0,10,-19,4,6,-8] 失败

问题描述

我对我的算法有疑问。不知何故,我不知道我的代码哪里错了。有人可以向我解释吗?谢谢你。

这是问题。

Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

我没有通过的测试用例:

[-2,0,10,-19,4,6,-8]

这是我的代码:

class Solution {
    public boolean checkIfExist(int[] arr) {
        for (int i = 0; i < arr.length; i++){
            for (int j = 0; j < arr.length; j++){
                int temp = arr[j] * 2;
                if (temp == arr[i]){
                    return true;
                }
            }
        }
    return false;
    }
}



  

标签: javaarrays

解决方案


问题是您总是将第 x 个元素与其自身进行比较。几乎总是不会有问题。但是,如果为 0(零),0 * 2 == 0则为 true。您需要做的就是跳过循环迭代 if i == j。实际上,如果您仔细查看您的任务,就会i != j在正式定义中说明。


推荐阅读