两数之和

86 阅读1分钟

两数之和

题目

输入一个递增的数字数组,和一个数字 n 。求和等于 n 的两个数字。
例如输入 [1, 2, 4, 7, 11, 15]15 ,返回两个数 [4, 11]

分析

注意题目的要点

  • 递增,从小打大排序
  • 只需要两个数字,而不是多个

利用递增的特性

数组是递增的

  • 随便找两个数
  • 如果和大于 n ,则需要向前寻找
  • 如果和小于 n ,则需要向后寻找 —— 二分法

双指针(指针就是索引,如数组的 index)

  • i 指向头,j 指向尾, 求 i + j 的和
  • 和如果大于 n ,则说明需要减少,则 j 向前移动(递增特性)
  • 和如果小于 n ,则说明需要增加,则 i 向后移动(递增特性)

时间复杂度降低到 O(n)

function findTwoNumSum1(arr, n) {
  let res = [];
  const length = arr.length;
  if (length === 0) return res;
  for (let i = 0; i < length - 1; i++) {
    const n1 = arr[i];
    let flag = false;
    for (let j = i + 1; j < length; j++) {
      const n2 = arr[j];
      if (n1 + n2 === n) {
        res.push(n1);
        res.push(n2);
        flag = true;
        break;
      }
    }
    if (flag) break;
  }
  return res;
}
function findTwoNumSum2(arr, n) {
  let res = [];
  const length = arr.length;
  if (length === 0) return res;
  let i = 0,
    j = length - 1;
  while (i < j) {
    const n1 = arr[i];
    const n2 = arr[j];
    const sum = n1 + n2;
    if (sum > n) {
      j--;
    } else if (sum < n) {
      i++;
    } else {
      res.push(n1);
      res.push(n2);
      break;
    }
  }
  return res;
}
// const arr = [2, 4, 7, 11, 15];
// console.time('findTwoNum1');
// console.log(findTwoNum1(arr, 15));
// console.timeEnd('findTwoNum1');
// console.time('findTwoNum2');
// console.log(findTwoNum2(arr, 15));
// console.timeEnd('findTwoNum2');