問題描述
這是我嘗試為這個問題尋找解決方案的第二天.
It's the second day I try to find a solution for this problem.
我有一個數組.
$datas;
$datas[0]; // 8000
$datas[1]; // 8001
$datas[2]; // 8003
$datas[3]; // 8004
我必須找到從 8000 開始的第一個缺失數字,在這種情況下是 8002.
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.
推薦答案
從低到高排序(如果還沒有排序)然后從最低開始遞增,檢查是否在數組中:
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
獲取第一個數字,在本例中為 8000 開始,當 $i
不在 $i
中時,in_array
條件終止循環數組.
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.
這篇關于找出數字序列中第一個缺失的數字的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!