I started to solve the problem on leetcode, this problem did not pass the test case, this is my attempt:
function checkIfExist($arr) {
$i = 0;
$j = 0;
$n = count($arr);
// 循环遍历数组
for($i; $i < $n; $i++) {
for($j; $j < $n; $j++) {
// 检查元素i和j是否不相同且N*2 = M
if ($i != $j && $arr[$i] * 2 == $arr[$j]) {
return true;
}
}
}
return false;
}
Could you please explain what mistake I made here?
This should work, try this (it's like one of those sorting algorithms). This is strange because the only difference is the initialization of
$iand$j.function checkIfExist($arr) { $n = count($arr); // 遍历数组 for($i = 0; $i < $n - 1; $i++) { for($j = $i + 1; $j < $n; $j++) { // 检查i和j的元素是否不相同且N*2 = M if ($i != $j && $arr[$i] * 2 == $arr[$j]) { return true; } } } return false; }In the for loop, the initialization of the $j and $i pointers completes the work
function checkIfExist($arr) { $n = count($arr); // 循环遍历数组 for($i = 0; $i < $n; $i++) { for($j = 0; $j < $n; $j++) { // 检查i和j元素是否不相同且N*2 = M if ($i != $j && $arr[$i] * 2 == $arr[$j]) { return true; } } } return false; }