Skip to main content

LeetCode 01 - Two Sum

  • Difficulty: Easy.
  • Related Topics: Array, Hash Table.
  • Link: leetcode

Problem

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].

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

Solution 1: two head

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/

var twoSum = function (nums, target) {
// only one result
if (nums.length === 2) {
return [0, 1];
}

for (let i = 0; i < nums.length - 1; i++) {
for (let j = 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target && i !== j) {
return [i, j];
}
}
}
};

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

Solution 2: hash map

var twoSum = function (nums, target) {
let obj = {};
for (let i = 0; i < nums.length; i++) {
if (target - nums[i] in obj) {
return [obj[target - nums[i]], i];
} else {
obj[nums[i]] = i;
}
}
};

Solution 3: one head solution

var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
let index = nums.indexOf(target - nums[i]);
if (index !== -1 && i !== index) {
return [i, index];
}
}
};