java - 为什么数组搜索错误对于 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;
}
}
解决方案
问题是您总是将第 x 个元素与其自身进行比较。几乎总是不会有问题。但是,如果为 0(零),0 * 2 == 0
则为 true。您需要做的就是跳过循环迭代 if i == j
。实际上,如果您仔细查看您的任务,就会i != j
在正式定义中说明。
推荐阅读
- mysql - MariaDB 查询加入百万条记录时速度慢
- ruby - 如何将表示 IEEE 754 浮点数的十六进制数字打印为 ruby 中的浮点数
- javascript - Laravel 使用 Ajax 以一种形式更新数据和文件?当方法/类型='PUT'
- javascript - 为什么这个函数不返回值?
- node.js - Heroku 部署在“修剪 devDependencies”步骤中继续失败
- string - 将用户输入转换为汇编中的所有大写字母 (NASM)
- javascript - 如何在不滚动整个页面的情况下向下滚动组件
- django - 使用 SSH 隧道的 PostgreSQL/psycopg2 密码验证
- python - 用python写一个特定的公式
- django - 在 Django 中,创建新子实例时我无法通过 url 传递 pk 值