JavaScript 中含有單位差值的最長子陣列
問題
我們需要編寫一個 JavaScript 函式,該函式以一個數字陣列 arr 作為第一個且唯一的引數
我們的函式應查詢並返回其中最大值與最小值之差恰好為 1 的子陣列的長度。
例如,如果函式的輸入為 −
const arr = [2, 4, 3, 3, 6, 3, 4, 8];
則輸出應為 −
const output = 5;
輸出說明
因為期望的子陣列為 [4, 3, 3, 3, 4]
示例
以下是程式碼 −
const arr = [2, 4, 3, 3, 6, 3, 4, 8];
const longestSequence = (arr = []) => {
const map = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {})
return Object.keys(map).reduce((max, key) => {
const nextKey = parseInt(key, 10) + 1
if (map[nextKey] >= 0) {
return Math.max(
max,
map[key] + map[nextKey],
)
}
return max
}, 0);
};
console.log(longestSequence(arr));輸出
以下是控制檯輸出 −
5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP