Skip to content
Merged
Show file tree
Hide file tree
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
23 changes: 23 additions & 0 deletions contains-duplicate/mkwkw.java
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 중 key값 만을 사용하고 계신것 같아서, set을 사용해도 괜찮지 않을까 싶습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//1. using map
//2. using set : why? It doesn't have to use a pair of key and value.

class Solution {
public boolean containsDuplicate(int[] nums) {
//Map<Integer, Boolean> appearance = new HashMap<>();
Set<Integer> appearance = new HashSet<>();

for(int i=0; i<nums.length; i++)
{
if(appearance.contains(nums[i]))
{
return true;
}
else
{
appearance.add(nums[i]);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Set을 활용한 접근 방식은 굉장히 좋은 것 같습니다. 고생하셨습니다!

위 부분에는 Early Return을 적용한다면, 더 가독성이 높아지지 않을까 생각이 들어 참고차 자료 공유드립니다🙏
https://thearchivelog.dev/article/are-early-returns-any-good/


return false;
}
}
43 changes: 43 additions & 0 deletions two-sum/mkwkw.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//Store the number and the index.
//There can be only 2 same numbers. <- there is exactly one solution

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {

map<int, vector<int>> numAndIndex;
vector<int> answer;

//map: key:nums[i], value:{indexs}
for(int i=0; i<nums.size(); i++)
{
numAndIndex[nums[i]].push_back(i);
}

for(int i=0; i<nums.size()-1; i++)
{
if(numAndIndex.contains(target-nums[i]))
{
//To pick another number, not own number
if(target-nums[i]==nums[i]&&numAndIndex[nums[i]].size()==2)
{
answer.push_back(numAndIndex[nums[i]][0]);
answer.push_back(numAndIndex[nums[i]][1]);
}
else if(target-nums[i]!=nums[i])
{
answer.push_back(numAndIndex[nums[i]][0]);
answer.push_back(numAndIndex[target-nums[i]][0]);
}
}

if(answer.size()==2)
{
break;
}
}

return answer;

}
};