数据解构和算法

55.算法->两数之和

2022-02-16  本文已影响0人  wo不是黄蓉

day7:两数之和(简单)
思路:

var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
    let index = nums.indexOf(target - nums[i]);
    if (index != i && index != -1) {
      return [i, index];
    }
  }
};
console.log(twoSum([3, 2, 4], 6));
执行结果

考虑重复值:

var twoSum = function (nums, target) {
  for (let i = 0; i < nums.length; i++) {
    let arr = findIndex(nums, target - nums[i]);
    for (let j = 0; j < arr.length; j++) {
      if (i != arr[j]) {
        return [i, arr[j]];
      }
    }
  }
};

var findIndex = function (array, num) {
  let indexArr = [];
  array.forEach((item, index) => {
    if (item === num) {
      indexArr.push(index);
    }
  });
  return indexArr;
};


执行结果

使用map存储得方式实现

var twoSum1 = function (nums, target) {
  let map = new Map();
  let result = [];
  nums.forEach((item, index) => {
    let flag = map.get(target - item);
    if (flag === undefined) {
      //说明没找到
      map.set(item, index);
    } else {
      result.push(flag, index);
    }
  });
  return result;
};
上一篇下一篇

猜你喜欢

热点阅读