写一个方法判断一组数字是连值
/**
* Checks if an array of numbers represents a consecutive sequence.
*
* @param {number[]} nums The array of numbers to check.
* @returns {boolean} True if the array is a consecutive sequence, false otherwise.
*/
function isConsecutive(nums) {
if (!nums || nums.length < 1) {
return true; // Empty or single-element array is considered consecutive
}
// Sort the array to easily check for consecutive numbers
nums.sort((a, b) => a - b);
// Check for consecutive elements
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1] + 1) {
return false;
}
}
return true;
}
// Example usage:
console.log(isConsecutive([1, 2, 3, 4, 5])); // Output: true
console.log(isConsecutive([5, 4, 3, 2, 1])); // Output: true
console.log(isConsecutive([1, 3, 5, 7])); // Output: false
console.log(isConsecutive([1, 2, 4, 5])); // Output: false
console.log(isConsecutive([1, 1, 2, 3])); // Output: false
console.log(isConsecutive([])); // Output: true
console.log(isConsecutive([5])); // Output: true
This function first handles the edge cases of empty or single-element arrays, considering them consecutive. Then, it sorts the input array numerically. Finally, it iterates through the sorted array, checking if each element is exactly one greater than the previous element. If it finds any element that breaks this pattern, it returns false
. Otherwise, if the loop completes without finding any discrepancies, it returns true
. This approach ensures that the function correctly identifies consecutive sequences regardless of the initial order of the numbers in the input array.