我对我的算法有一个问题。不知何故,我不知道我的代码哪里错了。有人能给我解释一下吗?谢谢。
以下是问题所在。
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;
}
}发布于 2020-07-01 15:11:41
问题是,您总是将第x个元素与其自身进行比较。几乎总是不会有什么问题。但是,如果为0(零),则0 * 2 == 0为true。如果为i == j,您需要做的就是跳过循环迭代。实际上,如果你仔细观察你的任务,就会发现i != j在正式定义中是这样的。
https://stackoverflow.com/questions/62671346
复制相似问题