Skip to content

[GUMUNYEONG] Week3 문제풀이 #398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 1, 2024
Merged
Changes from all commits
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/GUMUNYEONG.js
Copy link
Member

@DaleSeo DaleSeo Aug 31, 2024

Choose a reason for hiding this comment

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

입력으로 nums = [0, 0], target = 0이 주어진다면 어떨까요? [0, 1] 대신에 undefined가 반환될 것 같아서 여쭙니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

앗...!!!! 네 맞습니다..!! 테스트 케이스 이외에 다른 경우를 고려하지 못했네요..
다음부터는 좀 더 세심하게 여러 케이스를 생각해서 짜야겠습니다.
피드백 감사합니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
let result = [];
let numPair = {};

for (let i = 0; i < nums.length; i++) {
numPair[nums[i]] = target - nums[i];
}



for (const key in numPair) {
Copy link
Contributor

Choose a reason for hiding this comment

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

저도 비슷하게 풀었습니다!
제가 받은 코드 리뷰에서는 "적절한 자료구조를 활용해서 더 효율적인 방식으로 풀어볼 수 있을 것" 이라고 답변을 받았고 다른 풀이 법을 고민 해 봤습니다.
문영님도 해시맵(Map)과 같은 방법을 활용해 보시는 게 좋을 것 같다는 의견을 남깁니다!

let list = [];
const reverseKey = numPair[key];

if (parseInt(key) === numPair[reverseKey]) {
let firstNum;
let secNum;

if (parseInt(key) === reverseKey) {
firstNum = nums.indexOf(reverseKey);
secNum = nums.indexOf(reverseKey, firstNum + 1);
} else {
firstNum = nums.indexOf(parseInt(key));
secNum = nums.indexOf(reverseKey);
}

result.push(firstNum);
result.push(secNum);

return result;
}
}

};

// TC : O(n)
// 1. num 을 순회하며 numPair 객체를 만듦(num 길이 n)
// 2. numPair 를 순회하며 키-값이 대칭되는 첫번째 쌍을 찾음 (numPair 길이 n)
// 3. num을 순회하며 인덱스를 찾음 (num 길이 n)
// O(3n) 따라서 시간복잡도는 O(n)

// SC : O(n)
// 크기가 n만큼인 객체(numPair)를 생성하므로 공간 복잡도도 O(n)