-
-
Notifications
You must be signed in to change notification settings - Fork 195
[mallayon] Week 7 #941
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
[mallayon] Week 7 #941
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5e35f9c
add solution : 62. Unique Paths
mmyeon e6e48af
add solution : 200. Number of Islands
mmyeon 8d93ac6
add solution : 3. Longest Substring Without Repeating Characters
mmyeon 3c111b6
remove comment
mmyeon 3cd4f15
add solution : 206. Reverse Linked List
mmyeon d642590
add solution : 73. Set Matrix Zeroes
mmyeon 0527960
improve sliding window logic
mmyeon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
/** | ||
*@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>(); | ||
|
||
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; | ||
} | ||
|
||
// Map 사용해서 중복 발생시 start 인덱스가 점프하도록 개선 | ||
function lengthOfLongestSubstring(s: string): number { | ||
let start = 0, | ||
maxLength = 0; | ||
const map = new Map<string, number>(); | ||
|
||
for (let i = 0; i < s.length; i++) { | ||
const char = s[i]; | ||
// 중복 있는 경우, 중복문자의 다음 위치로 점프 | ||
if (map.has(char)) start = Math.max(start, map.get(char)! + 1); | ||
// 인덱스 갱신 | ||
map.set(char, i); | ||
|
||
maxLength = Math.max(maxLength, i - start + 1); | ||
} | ||
|
||
return maxLength; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
class ListNode { | ||
val: number; | ||
next: ListNode | null; | ||
constructor(val?: number, next?: ListNode | null) { | ||
this.val = val === undefined ? 0 : val; | ||
this.next = next === undefined ? null : next; | ||
} | ||
} | ||
|
||
/** | ||
* | ||
* @link https://leetcode.com/problems/reverse-linked-list/ | ||
* | ||
* 접근 방법 : | ||
* - 리스트 순회하면서 새로운 노드를 생성하고 기존 reversed 리스트의 head를 연결 | ||
* | ||
* 시간복잡도 : O(n) | ||
* - 리스트 노드 1회 순회하니까 | ||
* | ||
* 공간복잡도 : O(n) | ||
* - reversed 된 링크드 리스트 새로 만드니까 | ||
*/ | ||
|
||
function reverseList(head: ListNode | null): ListNode | null { | ||
if (head === null) return head; | ||
|
||
let headNode: ListNode | null = null; | ||
let currentNode: ListNode | null = head; | ||
|
||
while (currentNode !== null) { | ||
const newNode = new ListNode(currentNode.val, headNode); | ||
headNode = newNode; | ||
currentNode = currentNode.next; | ||
} | ||
|
||
return headNode; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
/** | ||
Do not return anything, modify matrix in-place instead. | ||
*/ | ||
/** | ||
* @link https://leetcode.com/problems/set-matrix-zeroes/description/ | ||
* | ||
* 접근 방법 : | ||
* - 행렬 순회하면서 0이 있는 행과 열을 rowsToZero과 colsToZero에 저장 | ||
* - 다시 행렬 순회하면서 rowsToZero과 colsToZero와 포함된 경우 0으로 변경 | ||
* | ||
* 시간복잡도 : O(m * n) | ||
* - m * n 행렬 크기만큼 순회 | ||
* | ||
* 공간복잡도 : O(m + n) | ||
* - m 행과 n 열 정보 저장 | ||
*/ | ||
function setZeroes(matrix: number[][]): void { | ||
const rows = matrix.length; | ||
const cols = matrix[0].length; | ||
const rowsToZero = new Set<number>(); | ||
const colsToZero = new Set<number>(); | ||
for (let row = 0; row < rows; row++) { | ||
for (let col = 0; col < cols; col++) { | ||
if (matrix[row][col] === 0) { | ||
rowsToZero.add(row); | ||
colsToZero.add(col); | ||
} | ||
} | ||
} | ||
|
||
for (let row = 0; row < rows; row++) { | ||
for (let col = 0; col < cols; col++) { | ||
if (rowsToZero.has(row) || colsToZero.has(col)) { | ||
matrix[row][col] = 0; | ||
} | ||
} | ||
} | ||
} | ||
|
||
// 공간 복잡도 O(m+n)을 O(1)로 개선하기 | ||
// set에 행과 열 정보 저장하던 방식을 set없이 첫 번째 행과 열을 활용하는 방법으로 변경 | ||
function setZeroes(matrix: number[][]): void { | ||
const rows = matrix.length; | ||
const cols = matrix[0].length; | ||
let hasZeroInFirstRow = false; | ||
let hasZeroInFirstCol = false; | ||
|
||
// 첫 번째 열에 0 있는지 여부를 플래그로 저장 | ||
for (let row = 0; row < rows; row++) { | ||
if (matrix[row][0] === 0) hasZeroInFirstCol = true; | ||
} | ||
|
||
// 첫 번째 행에 0 있는지 여부를 플래그로 저장 | ||
for (let col = 0; col < cols; col++) { | ||
if (matrix[0][col] === 0) hasZeroInFirstRow = true; | ||
} | ||
|
||
// 첫 번째 행과 열 제외하고 마커 설정하기 | ||
for (let row = 1; row < rows; row++) { | ||
for (let col = 1; col < cols; col++) { | ||
if (matrix[row][col] === 0) { | ||
matrix[0][col] = 0; | ||
matrix[row][0] = 0; | ||
} | ||
} | ||
} | ||
|
||
// 마커 기반으로 행렬에 반영 | ||
for (let row = 1; row < rows; row++) { | ||
for (let col = 1; col < cols; col++) { | ||
if (matrix[row][0] === 0 || matrix[0][col] === 0) matrix[row][col] = 0; | ||
} | ||
} | ||
|
||
// 첫 번째 행 업데이트 | ||
if (hasZeroInFirstRow) { | ||
for (let col = 0; col < cols; col++) { | ||
matrix[0][col] = 0; | ||
} | ||
} | ||
|
||
// 첫 번째 열 업데이트 | ||
if (hasZeroInFirstCol) { | ||
for (let row = 0; row < rows; row++) { | ||
matrix[row][0] = 0; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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에 저장된 인덱스를 참고해 한 번에 점프할 수 있습니다. 현재 풀이도 충분히 잘 작성되었지만, 혹시 다른 방법을 참고하고 싶으실까 해서 남겨봅니다. 고생 많으셨습니다
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Jay-Mo-99 안녕하세요!
말씀해주신대로 맵에 인덱스 저장하니까, 인덱스 개별로 관리하지 않아도 돼서 로직이 엄청 깔끔해지네요 !!
더 좋은 풀이법 이야기해주셔서 정말 감사합니다 😄
소중한 리뷰 덕분에 많이 배웠습니다! 이번주도 고생 많으셨습니다 !!! 👍