可以在 JavaScript 中将数组拆分为连续的子序列
问题
我们需要编写一个JavaScript函数,它接受一个有序整数数组arr作为第一个也是唯一的参数。
当且仅当我们可以将数组拆分为1个或多个子序列,使得每个子序列由连续整数组成并且长度至少为3时,我们的函数才应该返回true,否则返回false。
例如,如果函数的输入是
输入
const arr = [1, 2, 3, 3, 4, 5];
输出
const output = true;
输出说明
我们可以将它们分成两个连续的子序列-
1, 2, 3 3, 4, 5
示例
以下是代码-
const arr = [1, 2, 3, 3, 4, 5];
const canSplit = (arr = []) => {
const count = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {})
const needed = {}
for (const num of arr) {
if (count[num] <= 0) {
continue
}
count[num] -= 1
if (needed[num] > 0) {
needed[num] -= 1
needed[num + 1] = (needed[num + 1] || 0) + 1
} else if (count[num + 1] > 0 && count[num + 2]) {
count[num + 1] -= 1
count[num + 2] -= 1
needed[num + 3] = (needed[num + 3] || 0) + 1
} else {
return false
}
}
return true
}
console.log(canSplit(arr));输出结果true