Check if there is an element in the array that is twice N equal to M
P粉663883862
P粉663883862 2023-09-11 13:15:10
0
2
458

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?

P粉663883862
P粉663883862

reply all(2)
P粉116654495

This should work, try this (it's like one of those sorting algorithms). This is strange because the only difference is the initialization of $i and $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;
}
P粉323050780

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;
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!