我剛剛接觸php,前幾天面試過,面試官問了一個像下面這樣的問題。在PHP中使用PHP查找給定數組中缺少的數字
給定數組有99個數字,其中包含從1到100的數字 只有一個數字缺失。描述兩種不同的算法,找到你缺少的數字。算法應該針對低存儲和快速處理進行優化。輸出應顯示每個算法的執行時間。
我已經搜索了谷歌關於它,並知道它的一個常見的難題用於在採訪中要求。我找到了這樣的答案。
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
idx = i;
} else {
sum += arr[i];
}
}
// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length/2;
System.out.println("missing number is: " + (total - sum) + " at index " + idx);
但代碼是不是在PHP中,
u能請幫我找出PHP代碼和算法的名字。所以我可以在接下來的採訪中提高我的答案。
你嘗試轉換的是Java的代碼到PHP?它應該是相當直接的,當它說'arr.length'使用'count($ arr)'時,其餘的應該幾乎相同。 – aurbano