Files

1.8 KiB

title, tags, categories, description, cover, top_img, abbrlink, date
title tags categories description cover top_img abbrlink date
LeetCode刷题:twoSum
LeetCode
LeetCode
LeetCode twoSum题 https://upload.wikimedia.org/wikipedia/commons/1/19/LeetCode_logo_black.png https://upload.wikimedia.org/wikipedia/commons/1/19/LeetCode_logo_black.png ce131649 2021-10-19 18:48:41

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

nums = [2, 7, 11, 15];
console.log(nums);

total = nums[0] + nums[1];
console.log(total);

const twoSum = function (nums, target) {
  const totals = {};
  for (let i = 0; i < nums.length; i++) {
    if (total[nums[i]] >= 0) {
      return [total[nums[i]], i];
    }
  }
};
const twoSum = function (nums, target) {
  const comp = {};
  for (let i = 0; i < nums.length; i++) {
    if (comp[nums[i]] >= 0) {
      return [comp[nums[i]], i]
    }
    comp[target - nums[i]] = i;
  }
};
// O(n) - One-pass Hash Table
let twoSum = function (nums, target) {
  let map = new Map;
  for (let i = 0; i < nums.length; i++) {
    let completement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement), i]
    }
    map.set(nums[i], i);
  }
}
const twoSum = function (nums, target) {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const comp = target - nums[i];
    if (map.has(comp)) {
      return [map.get(comp), i];
    }
    map.set(nums[i], i);
  }
};