JavaScript 中最長的連續數字序列的長度


我們需要編寫一個 JavaScript 函式,該函式僅接收一個整數陣列作為第一個和唯一引數。

該函式應查詢並返回陣列中存在的最長連續遞增序列的長度(連續或不連續)。

例如 -

如果輸入陣列是 -

const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1];

則輸出應為 6,因為最長的連續遞增序列為 1、2、3、4、5、6。

示例

以下為程式碼 -

const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1];
const consecutiveSequence = (arr = []) => {
   const consecutiveRight = {};
   let max = 0;
   for (let i = 0; i < arr.length; i += 1) {
      let curr = arr[i];
      if (consecutiveRight[curr] !== undefined) {
         continue; // We already have this number.
         consecutiveRight[curr] = 1 + (consecutiveRight[curr + 1] || 0);
         while (consecutiveRight[curr - 1] !== undefined) {
            consecutiveRight[curr - 1] = consecutiveRight[curr] + 1;
            curr -= 1;
         }
         max = Math.max(max, consecutiveRight[curr]);
      }
      return max;
};
console.log(consecutiveSequence(arr));

輸出

以下為控制檯輸出 -

6

更新於:2021-1-19

457 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始
廣告內容
© . All rights reserved.