Home  >  Q&A  >  body text

Check if there is an element in the array that is twice N equal to M

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粉663883862P粉663883862377 days ago452

reply all(2)I'll reply

  • P粉116654495

    P粉1166544952023-09-12 10:25:48

    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;
    }
    

    reply
    0
  • P粉323050780

    P粉3230507802023-09-12 00:14:39

    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;
        }

    reply
    0
  • Cancelreply