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

[gitsunmin] WEEK4 Solution #420

Merged
merged 7 commits into from
Sep 5, 2024
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
29 changes: 29 additions & 0 deletions longest-consecutive-sequence/gitsunmin.ts
Copy link
Contributor

Choose a reason for hiding this comment

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

풀이 잘 보았습니다. 제가 TS에 익숙하지 않아서 질문드립니다만, 혹시 findStreaktakeWhile을 밖으로 빼야하는 이유가 있나요? 두개 다 메인함수에 집어넣어서 해결가능해 보여서 질문드립니다 😃

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* https://leetcode.com/problems/longest-consecutive-sequence
* time complexity : O(n)
* space complexity : O(n)
*/
const findStreak = (set: Set<number>) => (num: number): number => {
if (!set.has(num - 1)) return takeWhile(num, currentNum => set.has(currentNum)).length;
return 0;
};

const takeWhile = (start: number, predicate: (value: number) => boolean): number[] => {
const result: number[] = [];
let currentNum = start;
while (predicate(currentNum)) {
result.push(currentNum);
currentNum += 1;
}
Comment on lines +14 to +17
Copy link
Contributor

Choose a reason for hiding this comment

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

map 함수안에서 while문을 돌리는데 시간복잡도가 O(n)으로 산정되는 이유가 궁금해요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Sunjae95
아래에 작성해봤어요! 혹시 잘 못된 부분이 있다면 이야기 부탁드려요

  1. 각 숫자는 한 번만 순회됩니다:
    findStreak 함수는 연속된 수열의 시작점을 찾는 역할을 합니다. 연속된 수열의 시작점(num - 1이 존재하지 않는 숫자)에 대해서만 takeWhile 함수가 호출되고, 그 수열의 끝까지 while 루프가 실행됩니다. 한 번 수열이 처리되면 그 수열의 다른 숫자들은 다시 처리되지 않습니다.
    예를 들어, 배열 [100, 4, 200, 1, 3, 2]에서:
    • 1을 시작으로 takeWhile이 호출되어 수열 [1, 2, 3, 4]을 처리합니다.
    • 그 이후에는 2, 3, 4에 대해 set.has(num - 1) 조건이 참이므로 takeWhile은 호출되지 않으며, while 루프도 다시 돌지 않습니다.
  2. 각 숫자가 한 번만 while에서 처리됨:
    숫자가 이미 처리된 수열에 속하면 다시 while을 실행하지 않습니다. 이는 중복 처리를 피하는 로직으로, 숫자 n이 연속된 수열에 포함되어 있다면 takeWhile은 그 숫자를 최대 한 번만 처리하게 되어, 중복 없이 전체 nums 배열의 각 숫자는 한 번씩만 순회됩니다.
  3. 결론적으로 O(n):
    따라서 전체 숫자가 한 번만 순회되고, while 루프가 각 수열에서 한 번만 실행되므로 전체 시간 복잡도는 O(n)입니다. Set의 has 연산도 평균적으로 O(1)이기 때문에 시간 복잡도에 영향을 크게 미치지 않습니다.

return result;
}

const max = (maxStreak: number, currentStreak: number): number => Math.max(maxStreak, currentStreak);

function longestConsecutive(nums: number[]): number {
const numSet = new Set(nums);

return [...numSet]
.map(findStreak(numSet))
.reduce(max, 0);
}
21 changes: 21 additions & 0 deletions maximum-product-subarray/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* https://leetcode.com/problems/maximum-product-subarray
* time complexity : O(n)
* space complexity : O(1)
*/
function maxProduct(nums: number[]): number {
let r = nums[0];
let mx = 1, mn = 1;

for (let i = 0; i < nums.length; i++) {
const tempMx = mx * nums[i];
const tempMn = mn * nums[i];

mx = Math.max(tempMx, tempMn, nums[i]);
mn = Math.min(tempMx, tempMn, nums[i]);

r = Math.max(r, mx);
}

return r;
}
12 changes: 12 additions & 0 deletions missing-number/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* https://leetcode.com/problems/missing-number
* time complexity : O(n)
* space complexity : O(n)
*/
function missingNumber(nums: number[]): number {
const set = new Set<number>(nums);

for (let i = 0; i < set.size + 1; i++) if (!set.has(i)) return i;

return 0;
};
14 changes: 14 additions & 0 deletions valid-palindrome/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* https://leetcode.com/problems/valid-palindrome
* time complexity : O(n)
* space complexity : O(n)
*/

const clean = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]/g, "");

const reverse = (s: string): string => s.split("").reverse().join("");

function isPalindrome(s: string): boolean {
const cleaned = clean(s);
return cleaned === reverse(cleaned);
};
33 changes: 33 additions & 0 deletions word-search/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* https://leetcode.com/problems/word-search
* time complexity : O(m * n * 4^L)
Copy link
Contributor

Choose a reason for hiding this comment

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

2중 for문과 4번의 재귀호출을 잘파악하셨군요 🙌

* space complexity : O(L)
*/
const dfs = (r: number, c: number, index: number, board: string[][], word: string, rows: number, cols: number): boolean => {
if (index === word.length) return true;

if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[index]) return false;
const temp = board[r][c];

board[r][c] = '🚪';
const found = dfs(r + 1, c, index + 1, board, word, rows, cols) ||
dfs(r - 1, c, index + 1, board, word, rows, cols) ||
dfs(r, c + 1, index + 1, board, word, rows, cols) ||
dfs(r, c - 1, index + 1, board, word, rows, cols);

board[r][c] = temp;

return found;
};

function exist(board: string[][], word: string): boolean {
const rows = board.length;
const cols = board[0].length;

for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (dfs(r, c, 0, board, word, rows, cols)) return true;
}
}
return false;
}