Voyz's Studio.

LeetCode算法笔记-两数之和

字数统计: 140阅读时长: 1 min
2020/11/24 Share

LeetCode算法笔记–Day30

1. Two Sum

题目:

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
input: nums = [2, 7, 11, 15], target = 9
output: [0, 1]

My Answer:

1.Hash Map

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

Snip20200724_2.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let _res = [];
let _hashTable = new Map();
for (let i = 0; i < nums.length; i++) {
if( _hashTable.has(target - nums[i]) ){
_res.push(_hashTable.get(target - nums[i]));
_res.push(i);
return _res;
}else{
_hashTable.set(nums[i],i)
}
}
};

Snip20200724_1.png

CATALOG
  1. 1. LeetCode算法笔记–Day30
  2. 2. 1. Two Sum
    1. 2.0.0.0.1. 题目:
    2. 2.0.0.0.2. My Answer: