Find the first missing number in a sequence of numbers

谁说我不能喝 提交于 2019-12-02 16:31:45

问题


It's the second day I try to find a solution for this problem.

I have an array.

$datas;

$datas[0]; // 8000
$datas[1]; // 8001
$datas[2]; // 8003
$datas[3]; // 8004

I have to find the first missing number starting from 8000 in this case it's 8002.

My idea is to do somethig like this:

$datas[0] +1 = $datas[1]

if it's true port it's not free and I have to check the next one, if it's false it's the first free number.

I know it's not a correct syntax but I have some problems writing it in the right way.


回答1:


You can use array_diff to find the missing value.
I create a new array with values from min of $datas to max of $datas to compare against.
The return is what is missing.

$arr = range(min($datas),max($datas));

Var_dump(min(array_diff($arr,$datas)));

https://3v4l.org/ZmLAU

Can be a one liner too:

Var_dump(min(array_diff(range(min($datas),max($datas)), $datas)));



回答2:


Sort from lowest to highest (if not already sorted) and then increment from the lowest and check if it is in the array:

sort($datas); 
for($i=reset($datas); in_array($i, $datas); $i++);
echo $i;

reset gets the first number, in this case 8000 to start and the in_array condition terminates the loop when $i is not in the array.




回答3:


something like this should work

for($i=0;$i<count($datas);$i++){
  if($datas[$i] + 1 != $datas[$i+1]){
    echo($datas[$i] + 1 .' IS the missing number');
  }
}



回答4:


<?php

function get($data) {
    sort($data);
    $i = 0;
    while($i < count($data) - 2) {
        if ($data[$i+1] - $data[$i] != 1) return $data[$i] + 1;
        $i++;
    }

    return $data[count($data)-1] + 1;
}

echo get([ 8000, 8001, 8003, 8004,]);
echo get([ 8000, 8001, 8002, 8003, 8004,]);



回答5:


With something like this, it's pretty simple to just iterate through the array with a foreach loop.

foreach ($datas as $key=>$val) { 
  if ( $val +1 != $datas[$key+1] ) { 
    echo $val+1; // this is the first free value in the sequence
    }
  }


来源:https://stackoverflow.com/questions/48066561/find-the-first-missing-number-in-a-sequence-of-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!