const arr1 = [5, 2, 3, 4, 10]
const arr2 = [3, 2, 6, 8, 7]
const arr3 = [2, 3, 4, 5, 1]
const arr4 = [25, 20, 1, 11, 9]
const arr5 = [24, 12, 4, 13, 11]
const arr6 = [24, 12, 4, 13, 11, 23, 5, 18, 19, 20, 39, 22, 37, 40, 36, 38]
function fn(arr) {
// [24, 13, 12, 11, 4]
arr.sort(function (a, b) {
return b - a
})
const length = arr.length
const list = []
for (let i = 0; i < length; i++) {
list.push(1)
}
// console.log(list)
let index = 0
for (let i = 1; i < length; i++) {
const x = arr[i - 1]
const y = arr[i]
const z = x - y
if (z !== 1) {
if (list[index] > 1) {
list[++index] = -z
index++
} else if (z === 1) {
list[index] = -z
index++
}
}
if (z === 1) {
list[index] += z
}
}
// console.log(list)
const filteredList = list.filter(function (value, index, array) {
return value > 1
})
// console.log(filteredList)
let total = 0
if (filteredList.toString() !== '') {
total = Math.max.apply(null, filteredList)
}
console.log(`相连元素个数为 ${total}`)
}
fn(arr1)
fn(arr2)
fn(arr3)
fn(arr4)
fn(arr5)
fn(arr6)
image.png
https://codepen.io/MonguDykrai/pen/xQzyGw
网友评论