Skip to content

[soobing] WEEK01 Solution #1675

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
42 changes: 42 additions & 0 deletions house-robber/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* 문제 유형: DP
*
* 문제 설명
* - 바로 옆집을 한번에 털 수 없을때, 최대로 털 수 있는 돈을 구하는 문제
* - 함정은, 홀수의 합 vs 짝수의 합만 비교해서는 안된다. 2개 초과해서 털 수 있는 경우가 있음 (ex. [2, 1, 1, 2])
*
* 아이디어
* - DP 문제 답게 Top-down, Bottom-up 두 개 다 풀 수 있음
*/

function robBottomUp(nums: number[]): number {
const n = nums.length;
const dp = Array(n).fill(0);

if (n === 1) return nums[0];
if (n === 2) return Math.max(nums[0], nums[1]);

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

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

return dp[n - 1];
}

function robTopDown(nums: number[]): number {
const n = nums.length;
const memo = new Map<number, number>();

const dp = (i: number) => {
if (i < 0) return 0;
if (memo.has(i)) return memo.get(i);

const res = Math.max(dp(i - 1)!, dp(i - 2)! + nums[i]);
memo.set(i, res);
return res;
};
Comment on lines +33 to +40
Copy link
Contributor

Choose a reason for hiding this comment

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

현재 ! 연산자를 사용해도 코딩 테스트에선 문제는 없지만, 혹시 dp 함수의 반환 타입을 명시적으로 number로 지정해보는 건 어떨까요? const dp = (i: number): number => {
그렇게 하면 non-null assertion 없이도 컴파일러가 타입을 안전하게 추론해줘서 더 명확해질 것 같아요!!😊

return dp(n - 1)!;
}
71 changes: 71 additions & 0 deletions longest-consecutive-sequence/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* 문제 유형: 그래프(Union Find)
*
* 문제 설명
* - 주어진 배열에서 가장 긴 연속된 수열의 길이를 구하는 문제
*
* 아이디어
* 1) 중복된 수 제거 후 순회하며 값이 1차이 나는 항목끼리 합집합 만들기
*
* 미션
* - 더 빠른 풀이: HashSet 기반 Greedy로 풀어보기.
*
*/
class UnionFind {
parent: Map<number, number> = new Map();
size: Map<number, number> = new Map();

constructor(nums: number[]) {
for (const num of nums) {
this.parent.set(num, num);
this.size.set(num, 1);
}
}

find(x: number): number {
if (this.parent.get(x) !== x) {
this.parent.set(x, this.find(this.parent.get(x)!));
}

return this.parent.get(x)!;
}

union(x: number, y: number): void {
const rootX = this.find(x);
const rootY = this.find(y);

if (rootX === rootY) return;

const sizeX = this.size.get(rootX);
const sizeY = this.size.get(rootY);
if (sizeX < sizeY) {
this.parent.set(rootX, rootY);
this.size.set(rootY, sizeX + sizeY);
} else {
this.parent.set(rootY, rootX);
this.size.set(rootX, sizeX + sizeY);
}
}

getMaxSize(): number {
let max = 0;
for (const size of this.size.values()) {
max = Math.max(max, size);
}
return max;
}
}
function longestConsecutive(nums: number[]): number {
if (nums.length === 0) return 0;

const uniqueNums = Array.from(new Set(nums));
const uf = new UnionFind(uniqueNums);

for (const num of uniqueNums) {
if (uf.parent.has(num + 1)) {
uf.union(num, num + 1);
}
}

return uf.getMaxSize();
}
93 changes: 93 additions & 0 deletions top-k-frequent-elements/soobing2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* 문제 유형: Heap
*
* 문제 설명
* - 가장 빈도수가 많은 K개 Element 추출
*
* 아이디어
* 1) 빈도수 계산하여 index와 함께 Map에 저장, 빈도수를 기준으로 MinHeap 구성
* 2) 빈도수 Map을 순회하면서 MinHeap에 추가 + MinHeap의 크기가 K를 초과하면 최소값 제거 (미리미리 빈도수가 많은 K개 Element를 만들어나가는 형식)
* 3) MinHeap에 남아있는 Element들의 index를 반환
*
* 시간 복잡도: O(NlogK)
* 공간 복잡도: O(N)
*/
class MinHeap {
heap: [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.

[number, number][] 이 형식이 뭔지 궁금합니다!


insert(item: [number, number]) {
this.heap.push(item);
this.bubbleUp();
}

private bubbleUp() {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index][0] >= this.heap[parentIndex][0]) break;
[this.heap[index], this.heap[parentIndex]] = [
this.heap[parentIndex],
this.heap[index],
];
index = parentIndex;
}
}

extractMin(): [number, number] | undefined {
if (this.heap.length === 0) return undefined;
const min = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0 && end !== undefined) {
Comment on lines +37 to +40
Copy link
Contributor

Choose a reason for hiding this comment

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

if (this.heap.length === 0) return undefined;로 힙에 값이 없으면 undefined를 반환하도록 되어 있으니 end !== undefined는 없어도 되지 않을까요?

this.heap[0] = end;
this.sinkDown(0);
}
return min;
}

private sinkDown(index: number) {
const length = this.heap.length;
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let smallest = index;

if (left < length && this.heap[left][0] < this.heap[smallest][0]) {
smallest = left;
}
if (right < length && this.heap[right][0] < this.heap[smallest][0]) {
smallest = right;
}
if (index === smallest) break;

[this.heap[index], this.heap[smallest]] = [
this.heap[smallest],
this.heap[index],
];
index = smallest;
}
}

peek(): [number, number] | undefined {
return this.heap[0];
}

size(): number {
return this.heap.length;
}
}
function topKFrequent(nums: number[], k: number): number[] {
const freqMap = new Map<number, number>();
for (const num of nums) {
freqMap.set(num, (freqMap.get(num) ?? 0) + 1);
}

const minHeap = new MinHeap();
for (const [num, count] of freqMap.entries()) {
minHeap.insert([count, num]);
if (minHeap.size() > k) {
minHeap.extractMin();
}
}

return minHeap.heap.map(([_, num]) => num);
}