【algoexpert 算法笔记】1、两数之和

241 阅读1分钟

algoexpert 算法笔记

前言

leetcode链接:leetcode.cn/problems/tw… 题号:1

思路

  • 【不推荐】暴力破解:O(n^2) time | O(1) space
  • 【推荐】哈希:O(n) time | O(n) space
  • 【推荐】双指针:O(nlogn) time | O(1) space

暴力破解


// O(n^2) time | O(1) space
export function twoNumberSum(array: number[], targetSum: number) {
  for (let i = 0; i < array.length - 1; i++) {
    const firstNum = array[i];
    for (let j = i + 1; j < array.length; j++) {
      const secondNum = array[j];
      if (firstNum + secondNum === targetSum) {
        return [firstNum, secondNum];
      }
    }
  }
  return [];
}

哈希


// O(n) time | O(n) space
export function twoNumberSum(array: number[], targetSum: number) {
  const nums: {[key: number]: boolean} = {};
  for (const num of array) {
    const potentialMatch = targetSum - num;
    if (potentialMatch in nums) {
      return [potentialMatch, num];
    } else {
      nums[num] = true;
    }
  }
  return [];
}

双指针

// O(nlog(n)) | O(1) space
export function twoNumberSum(array: number[], targetSum: number) {
  array.sort((a, b) => a - b);
  let left = 0;
  let right = array.length - 1;
  while (left < right) {
    const currentSum = array[left] + array[right];
    if (currentSum === targetSum) {
      return [array[left], array[right]];
    } else if (currentSum < targetSum) {
      left++;
    } else if (currentSum > targetSum) {
      right--;
    }
  }
  return [];
}