是否能够排列数组形成连续序列 - JavaScript
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组并检查数组元素是否可以重新排列以形成序列。
例如 −
如果数组为 −
const arr = [3, 1, 4, 2, 5];
那么输出应该是 −
true
例子
以下是代码 −
const arr = [3, 1, 4, 2, 5];
const canBeConsecutive = (arr = []) => {
if(!arr.length){
return false;
};
const copy = arr.slice();
copy.sort((a, b) => a - b);
for(let i = copy[0], j = 0; j < copy.length; i++, j++){
if(copy[j] === i){
continue;
};
return false;
};
return true;
};
console.log(canBeConsecutive(arr));输出
以下是控制台中的输出 −
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP