Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions two-sum/naringst.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/

/**
* Runtime: 107ms, Memory: 49.52MB
* Time complexity: O(n^2)
* Space complexity: O(n^2)
*
* **/

var twoSum = function (nums, target) {
const answer = [];
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/

/**
* 다른 풀이: two의 sum 이니까 target - 현재 값을 한 뒤, 나머지 값이 배열에 있는지 찾는 방법.
* 이 과정에서 해시맵을 사용해서 target - 현재 값이 map 에 존재하면 return
* 없다면 map에 나머지 값과 그에 해당하는 인덱스를 추가한다.
* 그럼 추후에는 나머지 값을 map에서 O(1)로 찾기만 하면 된다.
*
* Runtime: 49ms, Memory: 49.52MB
* Time complexity: O(n)
* Space complexity: O(n)
* **/

var twoSum = function (nums, target) {
let map = new Map();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

프론트엔드 엔지니어로 일 할 땐 Map이 있다는 것만 알고 한 번도 써본 적이 없었는데 나리님께서 풀이에 사용하셨길래 좀 찾아보았습니다

(key, value) 쌍을 담는 컨테이너 역할로 사용하기엔 Map이 더 편한 구석이 많다는 것 알아갑니다 :D

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 현업에서는 아직 써본 적은 없는데, 이번 기회로 필요하다면 써봐야겠다는 생각을 했습니다! 감사합니다~


for (i = 0; i < nums.length; i++) {
if (map.has(target - nums[i])) return [map.get(target - nums[i]), i];
map.set(nums[i], i);
}
};