Skip to content

Commit b57c526

Browse files
Jaehyeon Robert HanJaehyeon Robert Han
authored andcommitted
two-sum solution
1 parent 4c8b68f commit b57c526

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

two-sum/Zioq.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function(nums, target) {
7+
// Initialize object to save remained value with index
8+
let remain_with_index_obj = {}
9+
10+
for ( let i =0; i<nums.length++; i++ ) {
11+
let remain = target - nums[i]; // Calculate reamined value to check
12+
13+
// If remained value found in the object, return current index and object's key
14+
if( remain_with_index_obj.hasOwnProperty(remain) ) {
15+
return [i, remain_with_index_obj[remain]]
16+
}
17+
18+
// Save the valu as key
19+
remain_with_index_obj[nums[i]] = i;
20+
}
21+
return null
22+
};
23+
24+
/*
25+
Time Complexity: O(n)
26+
Space Complexity: O(n)
27+
*/
28+
29+
console.log(twoSum([2,7,11,15], 9));
30+
console.log(twoSum([3,2,4], 6));

0 commit comments

Comments
 (0)