使用 JavaScript 中的 while 迴圈,找出包含連續數字的最長子陣列
我們需要編寫一個使用 while 語句的函式,該函式在包含正整數的陣列中找出最大連續子陣列的長度。
例如 -
如果輸入陣列為 -
const input = [6, 7, 8, 6, 12, 1, 2, 3, 4] --> [1,2,3,4]
那麼輸出應該為 -
4
如果輸入陣列為 -
const input = [5, 6, 1, 8, 9, 7] --> [8,9]
那麼輸出應該為 -
2
因此,讓我們為這個函式編寫程式碼 -
示例
const arr = [6, 7, 8, 6, 12, 1, 2, 3, 4]; const arr1 = [5, 6, 1, 8, 9, 7]; const findLongestSub = arr => { let count = 1, len = 0, max = 1; while(len < arr.length){ if(arr[len] === arr[len - 1] + 1){ count++; if(max < count){ max = count; } }else{ count = 1; }; len++; }; return max; }; console.log(findLongestSub(arr)); console.log(findLongestSub(arr1));
輸出
控制檯中的輸出將為 -
4 2
廣告