Skip to content

Commit 0383dda

Browse files
authored
Merge pull request #2388 from heesun-task/main
2 parents 457ffe5 + 44a3f84 commit 0383dda

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

contains-duplicate/heesun-task.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
/*
6+
Goal: return true if duplicated #, false if no duplicated number
7+
8+
Plan:
9+
- create a Set
10+
- loop num in nums
11+
- num exists in the Set -> return true
12+
- not exsits -> add the num in the Set, continue to the next loop
13+
- return false
14+
15+
space complexity: O(n)
16+
time complexity: O(n)
17+
*/
18+
var containsDuplicate = function(nums) {
19+
const seen = new Set();
20+
21+
for(const num of nums) {
22+
if (seen.has(num)) return true;
23+
seen.add(num);
24+
}
25+
return false;
26+
};

two-sum/heesun-task.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Goal: return indices of the two numbers such that they add up to target
3+
4+
Plan:
5+
- create a hash map (dict) to store number -> index
6+
- loop through nums with index i
7+
- get currentNum = nums[i]
8+
- compute pairNum = target - currentNum
9+
- if pairNum exists in dict
10+
-> return [dict[pairNum], i]
11+
- otherwise store currentNum in dict with its index
12+
- if no pair is found, return [-1, -1]
13+
14+
space complexity: O(n)
15+
time complexity: O(n)
16+
*/
17+
18+
var twoSum = function(nums, target) {
19+
const dict = {};
20+
21+
for (let i = 0; i < nums.length; i++) {
22+
const currentNum = nums[i];
23+
const pairNum = target - currentNum;
24+
25+
if (typeof dict[pairNum] === 'number') {
26+
return [dict[pairNum], i];
27+
} else {
28+
dict[currentNum] = i;
29+
}
30+
}
31+
32+
return [-1, -1];
33+
};

0 commit comments

Comments
 (0)