查詢陣列中前 n 個缺失數字的 PHP 程式
要查詢陣列中前 'n' 個缺失數字,PHP 程式碼如下所示:
示例
<?php
function missing_values($my_arr, $len, $n){
sort($my_arr); sort($my_arr , $len);
$i = 0;
while ($i < $n && $my_arr[$i] <= 0)
$i++;
$count = 0; $curr = 1;
while ($count < $n && $i < $len){
if ($my_arr[$i] != $curr){
echo $curr , " ";
$count++;
}
else
$i++;
$curr++;
}
while ($count < $n){
echo $curr , " ";
$curr++;
$count++;
}
}
$my_arr = array(6, 8, 0);
$len = sizeof($my_arr);
$n = 5;
print_r("The missing values of the array are ");
missing_values($my_arr, $len, $n);
?>輸出
The missing values of the array are 1 2 3 4 5
在上面的程式碼中,定義了一個名為 'missing_values' 的函式,它接收陣列、長度以及陣列中缺少的前幾個數字。
一個變數被賦值為 0,並檢查需要查詢的前幾個數字是否為 0 或更大。如果是 0,則將其遞增。
一個計數器被賦值為 0,並且 curr 值被賦值為 1。接下來,比較計數器值和陣列的前 'n' 個元素,並將第 'i' 個值與長度進行比較。如果 curr 與陣列中的某個元素相同,則計數器值遞增。否則,'i' 值遞增。在這個函式之外,定義了陣列,並將 'len' 變數賦值為陣列的長度。
前 'n' 個元素被賦值為 5。透過將這些值作為引數傳遞來呼叫函式,並在控制檯上列印輸出。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP