Skip to content

[mmyeon] Week 1 #1144

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 6 commits into from
Apr 4, 2025
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
22 changes: 0 additions & 22 deletions contains-duplicate/mmyeon.js

This file was deleted.

14 changes: 14 additions & 0 deletions contains-duplicate/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
*
* 접근 방법 :
* - set 자료구조에 nums 값 담아서 set의 크기와 배열의 길이를 비교하기
*
* 시간복잡도 : O(n)
* - nums 배열을 순회해서 set에 저장하니까 O(n)
*
* 공간복잡도 : O(n)
* - nums 배열의 길이만큼 set에 담으니까 O(n)
*/
function containsDuplicate(nums: number[]): boolean {
return nums.length !== new Set(nums).size;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

한줄로 깔끔하게 구현해주시고, 복잡도를 다 작성해주셔서 확인하기 편했습니다!
궁금한점은 nums를 Set로 변환할떄, 스프레드 연산자를 사용해서 작성하신 이유가 따로 있을까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

앗 이 부분은 불필요하게 스프레드 연산자가 사용되었네요!
수정하곘습니다. 꼼꼼하게 리뷰해주셔서 감사합니다!! 👍

34 changes: 0 additions & 34 deletions house-robber/mmyeon.js

This file was deleted.

50 changes: 50 additions & 0 deletions house-robber/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
*
* 접근 방법 :
* - 최적의 해를 구하기 위해서 dp 사용
* - 현재 인덱스까지 훔칠 수 있는 가장 큰 값을 dp에 저장
*
* 시간복잡도 : O(n)
* - nums 배열을 1회만 순회하니까 O(n)
*
* 공간복잡도 : O(n)
* - nums 배열 크기만큼 dp 배열에 저장
*/
function rob(nums: number[]): number {
const dp: number[] = [];

dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);

for (let i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}

return dp[nums.length - 1];
}

/**
*
* 접근 방법 : 공간 복잡도 O(1)로 최적화
* - 이전 두 값만 저장하는 방식으로 개선
*
* 시간복잡도 : O(n)
*
* 공간복잡도 : O(1)
* - 고정된 변수만 사용
*/
function rob(nums: number[]): number {
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);
Copy link
Contributor

Choose a reason for hiding this comment

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

nums.length 에 따른 예외처리도 처음부터 넣어서 안전하게 처리해주셨네요
dp배열을 없애고 필요한 값만 저장해 공간복잡도를 개선하는 부분이 참 인상적이네요! 많이배웠습니다


let prev2 = nums[0];
let prev1 = Math.max(nums[0], nums[1]);

for (let i = 2; i < nums.length; i++) {
const current = Math.max(prev1, prev2 + nums[i]);
prev2 = prev1;
prev1 = current;
}

return prev1;
}
46 changes: 0 additions & 46 deletions longest-common-subsequence/mmyeon.js

This file was deleted.

33 changes: 33 additions & 0 deletions longest-consecutive-sequence/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
*
* 접근 방법 :
* - 중복 숫자 제거하고 빠르게 조회하기 위해서 Set 사용
* - 연속된 숫자의 시작점(현재 숫자보다 작은 숫자가 없는 경우)를 찾아서 연속된 길이 카운트
* - 최대 길이 갱신
*
* 시간복잡도 : O(n)
* - Set 생성, 숫자 탐색 모두 O(n)
*
* 공간복잡도 : O(n)
* - 최악의 경우, nums 배열 크기만큼 set에 저장하니까 O(n)
*/
function longestConsecutive(nums: number[]): number {
const numSet = new Set(nums);
let longestLength = 0;

for (const num of numSet) {
if (!numSet.has(num - 1)) {
let currentLength = 1;
let currentNum = num + 1;

while (numSet.has(currentNum)) {
currentLength++;
currentNum++;
}

longestLength = Math.max(longestLength, currentLength);
}
}

return longestLength;
}
33 changes: 0 additions & 33 deletions top-k-frequent-elements/mmyeon.js

This file was deleted.

38 changes: 38 additions & 0 deletions top-k-frequent-elements/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
*
* 접근 방법 :
* - 정렬 사용하지 않고 o(n)을 풀기 위해서 숫자 빈도수를 배열 인덱스로 저장
* - 숫자 빈도스를 맵에 저장
* - 맵을 순회하면서, 빈도수를 배열에 저장 (동일 반도수 처리하기 위해서 2차원 배열 사용)
* - 배열을 역순으로 순회하면서 빈도수 기반의 값을 결과 배열에 저장
* - 결과 배열을 k개만큼 잘라서 리턴
*
* 시간복잡도 : O(n)
* - nums 배열 1회 순회하면서 맵에 저장하니까 O(n)
*
* 공간복잡도 : O(n)
* - nums 배열 길이만큼 맵과 2차원 배열에 정리하니까 O(n)
*/
function topKFrequent(nums: number[], k: number): number[] {
const numMap = new Map();

for (const num of nums) {
numMap.set(num, (numMap.get(num) ?? 0) + 1);
}

const storedArr: number[][] = Array(nums.length + 1)
Copy link
Contributor

Choose a reason for hiding this comment

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

저는 Map으로 중복을 제거하고, entries를 사용해 배열화한다음 sorting 해서 출력해주는것밖에 떠오르지않았는데
따로 정렬을 사용하지않고,빈도카운팅을해서 배열에 추가하는식으로 접근하신게 너무 신기했어요!
친절하게 주석을 달아주셔서 처음보는 개념인데도 이해가 쉬웠습니다. 감사합니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

저도 sorting 없이 풀려고 하니까 잘 떠오르지 않더라구요! 😄
O(n)으로 풀고 싶어서 다른 분들 풀이 참고했어요!
더 나은 풀이법 발견하면 넘 신기하더라구요!!

.fill(null)
.map(() => []);

for (const [num, frequency] of numMap) {
storedArr[frequency].push(num);
}

const result: number[] = [];

for (let i = storedArr.length - 1; i >= 0; i--) {
if (storedArr[i].length > 0) result.push(...storedArr[i]);
}

return result.slice(0, k);
}
27 changes: 27 additions & 0 deletions two-sum/mmyeon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,30 @@ function twoSum(nums: number[], target: number): number[] {
map.set(nums[i], i);
}
}

/**
*
* 접근 방법 :
* - 현재 숫자가 확인한 숫자들 목록에 있으면 해당 숫자의 인덱스와 현재 인덱스를 바로 리턴
* - 숫자들 목록에 없으면 숫자와 인덱스를 map에 저장
*
* 시간복잡도 : O(n)
* - nums 배열을 1회만 순회하니까 O(n)
*
* 공간복잡도 : O(n)
* - 최악의 경우, nums 배열 크기만큼 map에 저장하니까 O(n)
*/
function twoSum(nums: number[], target: number): number[] {
const seenNumbers = new Map<number, number>();
Copy link
Contributor

Choose a reason for hiding this comment

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

new 이후에 free가 없어서 검색해 봤는데 javascript는 new 이후에 free 가 필요 없군요
새로운 사실을 알았습니다. 감사합니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@PDKhan
안녕하세요 반갑습니다!
리뷰 남겨주셔서 감사해요.

어떤 언어 사용하시는지 궁금해서 PR 체크해봤는데, 제 다음 PR 작성자가 아니시더라구요.
아마 리뷰어 할당에 착오가 있으셨던 것 같아요.

PDKhan님 PR 이전 PR에 다시 한 번 할당 부탁드립니다~
제 PR 리뷰어는 제가 수정하겠습니다!

Copy link
Contributor

Choose a reason for hiding this comment

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

@mmyeon 제가 PR을 작성했다가 삭제해서 그렇게 되었습니다.
혼동을 드려 죄송합니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@PDKhan
아하 그러셨군요!
리뷰 다시 한번 감사드려요 :)
1주차 문제 풀이 파이팅입니다!!


for (let i = 0; i < nums.length; i++) {
const neededValue = target - nums[i];
if (seenNumbers.has(neededValue)) {
return [i, seenNumbers.get(neededValue)!];
}

seenNumbers.set(nums[i], i);
}

return [];
}