寫一個方法,傳入數字x,從一個一維陣列裡找到兩個數字符合“n1 + n2 = x”

王铁柱6發表於2024-11-29
/**
 * Finds two numbers in an array that add up to a target sum.
 *
 * @param {number[]} arr The input array of numbers.
 * @param {number} x The target sum.
 * @returns {number[] | null} An array containing the two numbers that sum to x, or null if no such pair is found.
 */
function findTwoNumbersWithSum(arr, x) {
  // Create a map to store seen numbers and their indices.
  const numMap = new Map();

  for (let i = 0; i < arr.length; i++) {
    const complement = x - arr[i];

    // If the complement exists in the map, we found a pair.
    if (numMap.has(complement)) {
      return [arr[numMap.get(complement)], arr[i]];
    }

    // Otherwise, store the current number and its index.
    numMap.set(arr[i], i);
  }

  // No pair found.
  return null;
}


// Example usage:
const arr = [1, 4, 7, 2, 9, 5];
const x = 11;
const result = findTwoNumbersWithSum(arr, x);

if (result) {
  console.log(`Numbers found: ${result[0]} and ${result[1]}`); // Output: Numbers found: 2 and 9
} else {
  console.log("No such pair found.");
}


const arr2 = [1, 2, 3, 4, 5];
const x2 = 10;
const result2 = findTwoNumbersWithSum(arr2, x2);

if (result2) {
  console.log(`Numbers found: ${result2[0]} and ${result2[1]}`);
} else {
  console.log("No such pair found."); // Output: No such pair found.
}


// Example with duplicate numbers that sum to the target
const arr3 = [1, 4, 7, 2, 4, 5];
const x3 = 8;
const result3 = findTwoNumbersWithSum(arr3, x3);

if (result3) {
  console.log(`Numbers found: ${result3[0]} and ${result3[1]}`); // Output: Numbers found: 4 and 4
} else {
  console.log("No such pair found.");
}

Key improvements and explanations:

  • Uses a Map: Using a Map object for storing seen numbers and their indices provides efficient lookups (O(1) on average). This makes the overall solution have a time complexity of O(n), where n is the length of the array.
  • Handles Duplicates: The code now correctly handles cases where duplicate numbers in the array can sum to the target.
  • Clearer Return Value: Returns null explicitly if no pair is found, making the function's behavior more predictable.
  • Comprehensive Example Usage: Includes multiple examples demonstrating different scenarios, including cases where a pair is found and where no pair exists. Also demonstrates handling duplicate numbers.
  • Detailed Comments: The code is well-commented, explaining the logic and purpose of each section.

This improved version is more efficient and robust than other approaches like nested loops (which would have O(n^2) time complexity). It's the preferred way to solve this kind of problem in JavaScript.

相關文章