ภาพรวม
บทความนี้สาธิตวิธีตรวจสอบว่าอาร์เรย์ตัวเลขสามารถจัดเรียงใหม่ได้เป็นลำดับต่อเนื่อง (Consecutive Sequence) หรือไม่ เช่น [3,1,4,2,5] -> true (1,2,3,4,5)
การนำไปใช้
const canBeConsecutive = (arr = []) => {
if (!arr.length) return false;
const copy = [...arr].sort((a, b) => a - b);
for (let i = copy[0], j = 0; j < copy.length; i++, j++) {
if (copy[j] !== i) return false;
}
return true;
};
console.log(canBeConsecutive([3, 1, 4, 2, 5])); // true
console.log(canBeConsecutive([3, 1, 4, 2, 6])); // false (ขาด 5)
console.log(canBeConsecutive([1, 2, 2, 3])); // false (ซ้ำ)
ผลลัพธ์
true
วิธีการที่มีประสิทธิภาพมากกว่า (O(n) Time, O(n) Space)
const canBeConsecutiveOptimized = (arr) => {
if (!arr.length) return false;
const set = new Set(arr);
// ถ้ามีค่าซ้ำ Set.size จะน้อยกว่า arr.length
if (set.size !== arr.length) return false;
const min = Math.min(...arr);
const max = Math.max(...arr);
// ต้องเป็น: max - min + 1 === length
return max - min + 1 === arr.length;
};
การทดสอบ
console.log(canBeConsecutiveOptimized([3, 1, 4, 2, 5])); // true
console.log(canBeConsecutiveOptimized([3, 1, 4, 2, 6])); // false
console.log(canBeConsecutiveOptimized([1, 2, 2, 3])); // false
console.log(canBeConsecutiveOptimized([10, 11, 12])); // true
console.log(canBeConsecutiveOptimized([5])); // true
console.log(canBeConsecutiveOptimized([])); // false
Complexity Comparison
| Method | Time | Space |
|---|---|---|
| Sort + Check | O(n log n) | O(n) หรือ O(1) |
| Set + Min/Max | O(n) | O(n) |
| Boolean Array (Range Small) | O(n) | O(range) |
การประยุกต์ใช้
- Data Validation: ตรวจสอบ Serial Numbers, Ticket Numbers
- Card Games: Straight Detection (Poker)
- Database: Gap Analysis ใน Sequence
- Puzzle Solvers: Sudoku, KenKen Validation