在 JavaScript 中找到陣列中不存在的最小正整數
我們需要編寫一個 JavaScript 函式,其將陣列中的整數作為第一個且唯一的引數。
我們的函式應查詢並返回陣列中不存在的最小正整數。
例如,
如果輸入陣列是,
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
那麼輸出應該是,
const output = 5;
因為 1、2、3、4 已存在於陣列中,而 5 是陣列中缺少的最小正整數。
示例
以下是程式碼,
const arr = [4, 2, -1, 0, 3, 9, 1, -5]; const findSmallestMissing = (arr = []) => { let count = 1; if(!arr?.length){ return count; }; while(arr.indexOf(count) !== -1){ count++; }; return count; }; console.log(findSmallestMissing(arr));
輸出
以下是控制檯輸出,
5
廣告