Skip to content

Commit

Permalink
solve: two sum
Browse files Browse the repository at this point in the history
  • Loading branch information
wogha95 committed Aug 25, 2024
1 parent 6388615 commit f81a82c
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions two-sum/wogha95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// 2์ฐจ: index๋ฅผ ๊ฐ’์œผ๋กœ ๊ฐ–๋Š” Map์„ ํ™œ์šฉํ•˜์—ฌ ํ•œ๋ฒˆ์˜ ์ˆœํšŒ๋กœ ๋‹ต์•ˆ ๋„์ถœ
// TC: O(N)
// SC: O(N)

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const valueIndexMap = new Map();

for (let index = 0; index < nums.length; index++) {
const value = nums[index];
const anotherValue = target - value;

if (valueIndexMap.has(anotherValue)) {
return [index, valueIndexMap.get(anotherValue)];
}

valueIndexMap.set(value, index);
}
};

// 1์ฐจ: ์ •๋ ฌ ํ›„ ํˆฌํฌ์ธํ„ฐ ํ™œ์šฉ
// TC: O(N * logN)
// SC: O(N)

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const sortedNums = nums
.map((value, index) => ({ value, index }))
.sort((a, b) => a.value - b.value);
let left = 0;
let right = sortedNums.length - 1;

while (left < right) {
const sum = sortedNums[left].value + sortedNums[right].value;
if (sum < target) {
left += 1;
} else if (sum > target) {
right -= 1;
} else {
return [sortedNums[left].index, sortedNums[right].index];
}
}
};

0 comments on commit f81a82c

Please sign in to comment.