Skip to content
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

[mallayon] Week 7 #941

Merged
merged 7 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
36 changes: 36 additions & 0 deletions longest-substring-without-repeating-characters/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
*@link https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
*
* 접근 방법 :
* - 슬라우딩 윈도우와 set 사용해서 중복없는 문자열 확인
* - 중복 문자 발견하면 윈도우 축소
*
* 시간복잡도 : O(n)
* - 각 문자 순회하니까
*
* 공간복잡도 : O(n)
* - 중복 없는 경우 최대 n개의 문자 set에 저장
*/
function lengthOfLongestSubstring(s: string): number {
let start = 0,
end = 0,
maxLength = 0;
const set = new Set<string>();
Copy link
Contributor

Choose a reason for hiding this comment

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

안녕하세요, set을 사용해 중복 문자 처리가 용이한 윈도우 구간을 설정하고, start와 end로 슬라이딩을 구현하신 구조를 잘 봤습니다. 효율적인 풀이 방법이라고 생각합니다. 👍

덧붙여, map을 사용하면 문자와 해당 인덱스를 함께 저장할 수 있어 중복 문자가 발견되었을 때 start를 한 칸씩 이동하는 대신, map에 저장된 인덱스를 참고해 한 번에 점프할 수 있습니다. 현재 풀이도 충분히 잘 작성되었지만, 혹시 다른 방법을 참고하고 싶으실까 해서 남겨봅니다. 고생 많으셨습니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Jay-Mo-99 안녕하세요!
말씀해주신대로 맵에 인덱스 저장하니까, 인덱스 개별로 관리하지 않아도 돼서 로직이 엄청 깔끔해지네요 !!
더 좋은 풀이법 이야기해주셔서 정말 감사합니다 😄
소중한 리뷰 덕분에 많이 배웠습니다! 이번주도 고생 많으셨습니다 !!! 👍


while (end < s.length) {
const char = s[end];

// 중복이 있으면 윈도우 축소
if (set.has(char)) {
set.delete(s[start]);
start++;
} else {
// 중복 없으면 set에 문자 추가, 윈도우 확장
set.add(char);
maxLength = Math.max(maxLength, end - start + 1);
end++;
}
}

return maxLength;
}
60 changes: 60 additions & 0 deletions number-of-islands/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
*@link https://leetcode.com/problems/number-of-islands/
*
* 접근 방법 :
* - 섬의 시작점에서 끝까지 탐색해야 하므로 DFS 사용
* - 방문한 섬은 중복 탐색 방지하기 위해서 방문 후 값 변경 처리
*
* 시간복잡도 : O(m * n)
* - 2차원 배열 전체를 순회하므로 O(m * n)
*
* 공간복잡도 : O(m * n)
* - DFS 호출 스택 최대 깊이가 m * n 만큼 쌓일 수 있다.
*/

function numIslands(grid: string[][]): number {
let count = 0;
const rows = grid.length;
const cols = grid[0].length;

// 상하좌우 탐색 방향 배열
const directions = [
[0, -1],
[0, 1],
[-1, 0],
[1, 0],
];

// 현재 위치에서 연결된 모든 섬 탐색
const dfs = (row: number, col: number) => {
// 종료 조건 : 범위 벗어나거나, 이미 방문한 경우
if (
row < 0 ||
row >= rows ||
col < 0 ||
col >= cols ||
grid[row][col] === "0"
)
return;

// 현재 위치 방문 처리
grid[row][col] = "0";

// 상하좌우 탐색
for (const [x, y] of directions) {
dfs(row + x, col + y);
}
};

for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
// 섬의 시작점인 경우
if (grid[row][col] === "1") {
count++;
dfs(row, col);
}
}
}

return count;
}
39 changes: 39 additions & 0 deletions unique-paths/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @link https://leetcode.com/problems/unique-paths/
*
* 접근 방법 :
* - 시작부터 끝까지 누적된 경로의 수 찾아야 하니까 dp 사용
* - 첫 번째 행과, 첫 번째 열은 1로 고정이라서 dp 배열을 1로 초기화함
* - 점화식 : dp[x][y] = dp[x-1][y] + dp[x][y-1]
*
* 시간복잡도 : O(m * n)
* - m * n 행렬 크기만큼 순회하니까 O(m * n)
*
* 공간복잡도 : O(m * n)
* - 주어진 행렬 크기만큼 dp 배열에 값 저장하니까 O(m * n)
*/
function uniquePaths(m: number, n: number): number {
// m x n 배열 선언
const dp = Array.from({ length: m }, () => Array(n).fill(1));

for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}

return dp[m - 1][n - 1];
}

// 공간 복잡도를 O(n)으로 최적화하기 위해서 1차원 dp 배열 사용
function uniquePaths(m: number, n: number): number {
const rows = Array(n).fill(1);

for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
rows[j] = rows[j] + rows[j - 1];
}
}

return rows[n - 1];
}
Loading