LeetCode - 1. Two Sum




Thoughts:


I think hash map is a more efficient way to solve this one.

The time complexity will be O(n).

Instead of using object, I can use Map to store.

Map has a better performance when doing update more frequently.

The key will be the diff between target and current number,

if current number fits the key, then return [map.get(diff), i].

The value will be the index of the current number



Code:


/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const diff = target - nums[i];
    if (map.has(diff)) {
      return [map.get(diff), i];
    }
    map.set(nums[i], i);
  }
};


Reference


Original link
Map vs Object

Copyright © 2024 | All rights reserved.