Can the for loop be eliminated from this piece of PHP code?

后端 未结 10 1094
夕颜
夕颜 2020-12-11 04:59

I have a range of whole numbers that might or might not have some numbers missing. Is it possible to find the smallest missing number without using a loop structure? If ther

10条回答
  •  离开以前
    2020-12-11 05:52

    Technically, you can't really do without the loop (unless you only want to know if there's a missing number). However, you can accomplish this without first sorting the array.

    The following algorithm uses O(n) time with O(n) space:

    $range = [0, 1, 2, 3, 4, 6, 7];
    
    $N = count($range);
    $temp = str_repeat('0', $N); // assume all values are out of place
    
    foreach ($range as $value) {
        if ($value < $N) {
            $temp[$value] = 1; // value is in the right place
        }
    }
    
    // count number of leading ones
    echo strspn($temp, '1'), PHP_EOL;
    

    It builds an ordered identity map of N entries, marking each value against its position as "1"; in the end all entries must be "1", and the first "0" entry is the smallest value that's missing.

    Btw, I'm using a temporary string instead of an array to reduce physical memory requirements.

提交回复
热议问题