Two Sum

Leetcode practice log

Posted by Rui on 15-09-2021
Estimated Reading Time 1 Minutes
Words 275 In Total
Viewed Times

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

First Try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var i=0;
var l = nums.length-1;
for(i;i<=l;i++){
for(j=i+1;j<=l;j++){
if (nums[i]+nums[j] == target){
return [i,j]
}
}
}

};

Runtime: 112 ms, faster than 45.07% of JavaScript online submissions for Two Sum.
Memory Usage: 39.5 MB, less than 73.12% of JavaScript online submissions for Two Sum.

Feedback and improve

do not use var in a function(), use let.
Time complexity:o(n2); space complexity:o(1)
we can use map to reduce time complexity, by sacrificing space.
map{[kay:value],[key:value],[key:value],…}
map[key]=value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let map = {}
for(i=0; i< nums.length; i++){
let value = nums[i]
let pairvalue = target-nums[i]
if(map[pairvalue] !== undefined){
return[map[pairvalue],i]
}else{
map[value]=i
}
}

};

Runtime: 64 ms, faster than 99.36% of JavaScript online submissions for Two Sum.
Memory Usage: 40 MB, less than 55.97% of JavaScript online submissions for Two Sum.


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !