Skip to content

Commit 6b72441

Browse files
refactor: contains-duplicate
1 parent 3856037 commit 6b72441

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

two-sum/grapefruitgreentealoe.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,27 @@ var twoSum = function (nums, target) {
2222
}
2323
}
2424
};
25+
26+
var twoSum2 = function (nums, target) {
27+
for (let i = 0; i < nums.length; i++) {
28+
//시간복잡도 O(N)
29+
const subNum = target - nums[i]; // 공간 O(1)
30+
if (nums.includes(subNum) && nums.indexOf(subNum) !== i) {
31+
//시간복잡도 O(N). 2중포문과 같은 효과.
32+
return [i, nums.indexOf(subNum)];
33+
}
34+
}
35+
};
36+
37+
//Better answer
38+
var twoSum3 = function (nums, target) {
39+
// map으로 관리하여 indexing 최적화
40+
const numMap = new Map();
41+
for (let i = 0; i < nums.length; i++) {
42+
const subNum = target - nums[i];
43+
if (numMap.has(subNum)) {
44+
return [i, numMap.get(subNum)];
45+
}
46+
numMap.set(nums[i], i);
47+
}
48+
};

0 commit comments

Comments
 (0)