Home > Mobile >  Check If N == M*2 in the array
Check If N == M*2 in the array

Time:09-10

I'm starting solving problem on leetcode, this problem didn't pass the test cases, this my try:

function checkIfExist($arr) {
    
    $i = 0;
    $j = 0;
    $n = count($arr);
    
    // loop over the array
    for($i; $i < $n; $i  ) {
        for($j; $j < $n; $j  ) {    
            // check if element of i and j not the same and N*2 = M
            if ($i != $j && $arr[$i] * 2 == $arr[$j]) {
                return true;
            }
        }
    }
    return false;
}

Can please explain to me where I did the error here?

CodePudding user response:

This should work, try this though (it's like one of the sort algorithms). That is weird because only difference is the initialization of the $i and $j

function checkIfExist($arr) {
    
    $n = count($arr);
    
    // loop over the array
    for($i = 0; $i < $n - 1; $i  ) {
        for($j = $i   1; $j < $n; $j  ) {    
            // check if element of i and j not the same and N*2 = M
            if ($i != $j && $arr[$i] * 2 == $arr[$j]) {
                return true;
            }
        }
    }
    return false;
}

CodePudding user response:

The initializing of $j and $i pointer inside the for-loop done the work

 function checkIfExist($arr) {
    
        $n = count($arr);
    
        // loop over the array
        for($i = 0; $i < $n; $i  ) {
            for($j = 0; $j < $n; $j  ) {    
                // check if element of i and j not the same and N*2 = M
                if ($i != $j && $arr[$i] * 2 == $arr[$j]) {
                    return true;
                }
            }
        }
        return false;
    }
  • Related