Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาตัวเลขที่แตกต่าง (Odd One Out) ในอาร์เรย์ JavaScript

ภาพรวม

บทความนี้สาธิตวิธีหาตัวเลขที่ "แตกต่างจากกลุ่ม" ในอาร์เรย์ที่มีค่าส่วนใหญ่เหมือนกัน และมีเพียง 1 ตัวที่ต่าง

ตัวอย่าง

Input:  [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
Output: 2 (ตัวแรกคือค่าที่ต่าง)

การนำไปใช้ (มี Bug ใน Logic)

const findUnlike = (arr) => {
  for (let i = 1; i < arr.length - 1; i++) {
    if (arr[i] - arr[i-1] !== 0 && arr[i] - arr[i+1] === 0) {
      return arr[i-1];
    } else if (arr[i] - arr[i-1] !== 0 && arr[i] - arr[i+1] === 0) {
      return arr[i]; // Duplicate condition!
    } else if (arr[i] - arr[i-1] === 0 && arr[i] - arr[i+1] !== 0) {
      return arr[i+1];
    }
  }
};

ผลลัพธ์

2

วิธีที่ถูกต้องและง่ายกว่า

// ใช้ Frequency Count
const findUnique = (arr) => {
  const freq = new Map();
  for (const num of arr) {
    freq.set(num, (freq.get(num) || 0) + 1);
  }
  for (const [num, count] of freq) {
    if (count === 1) return num;
  }
  return null;
};

// ใช้ XOR (ถ้ามีค่าซ้ำคู่ และค่า Unique เดียว)
const findUniqueXOR = (arr) => arr.reduce((a, b) => a ^ b, 0);
// [2, 4, 4, 4, 4...] -> 2 ^ 4 ^ 4 ^ 4... = 2 (ถ้า 4 ซ้ำจำนวนคู่)

// ใช้ Sort
const findUniqueSort = (arr) => {
  const sorted = [...arr].sort((a, b) => a - b);
  if (sorted[0] !== sorted[1]) return sorted[0];
  return sorted[sorted.length - 1];
};

กรณีที่ซับซ้อนกว่า

// หา Element ที่ปรากฏ Odd Number of Times
const findOddOccurrence = (arr) => 
  arr.reduce((a, b) => a ^ b, 0);

// หา 2 ตัวที่ Unique (อื่นๆ ซ้ำคู่)
const findTwoUnique = (arr) => {
  const xorAll = arr.reduce((a, b) => a ^ b, 0);
  const diffBit = xorAll & -xorAll; // Rightmost set bit
  
  let a = 0, b = 0;
  for (const num of arr) {
    if (num & diffBit) a ^= num;
    else b ^= num;
  }
  return [a, b];
};

การประยุกต์ใช้

  • Error Detection: หา Corrupted Data
  • Network: หา Packet ที่หาย/ซ้ำ
  • Quality Control: หาสินค้าผิดปกติ
  • Puzzle Solving: Single Number Problem (LeetCode 136)

ข้อควรระวัง

  • โค้ดต้นฉบับมี Logic Bug (Duplicate Condition)
  • XOR Method ต้องการ: ค่าอื่นๆ ซ้ำจำนวนคู่ เท่านั้น
  • Frequency Map ใช้ได้ทั่วไป แต่ใช้ Space O(n)