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

[선재] WEEK09 Solution #515

Merged
merged 6 commits into from
Oct 12, 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
32 changes: 32 additions & 0 deletions find-minimum-in-rotated-sorted-array/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @description
* brainstorming:
* brute force
*
* n = length of head
* time complexity: O(n)
* space complexity: O(1)
*/
var findMin = function (nums) {
let answer = 5000;
nums.forEach((num) => (answer = Math.min(answer, num)));

return answer;
};

/* n = length of head
* time complexity: O(n)
* space complexity: O(1)
*/
var findMin = function (nums) {
let answer = nums[0];
if (nums.length === 1) return answer;
if (answer < nums[nums.length - 1]) return answer;

for (let i = nums.length - 1; i >= 0; i--) {
if (answer < nums[i]) return answer;
answer = nums[i];
}
Comment on lines +24 to +29
Copy link
Contributor

Choose a reason for hiding this comment

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

answer < nums[nums.length - 1] 조건문이 for문 안에 있는 if문에 포함되어 제거 가능해보입니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

오호?! 그러네요 중복되는 로직이었군요..!
감사합니다.


return answer;
};
21 changes: 21 additions & 0 deletions linked-list-cycle/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @description
* brainstorming:
* hash table
*
* n = length of head
* time complexity: O(n)
* space complexity: O(n)
*/
var hasCycle = function (head) {
const set = new Set();
let node = head;

while (node) {
if (set.has(node)) return true;
set.add(node);
node = node.next;
}

return false;
};
23 changes: 23 additions & 0 deletions maximum-subarray/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @description
* n = length of nums
* time complexity: O(n)
* space complexity: O(1)
*/
var maxSubArray = function (nums) {
let sum = 0;
let answer = nums[0];

for (let end = 0; end < nums.length; end++) {
if (sum < 0) {
sum = nums[end];
} else if (sum + nums[end] >= 0) {
sum += nums[end];
} else {
sum = nums[end];
}

answer = Math.max(answer, sum);
}
return answer;
};
41 changes: 41 additions & 0 deletions minimum-window-substring/sunjae.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @description
* brainstorming:
* two pointer + hash table
*
* n = length of s
* m = length of t
* time complexity: O(n*n)
* space complexity: O(n)
*/
var minWindow = function (s, t) {
const requiredMap = t.split("").reduce((map, char) => {
map.set(char, (map.get(char) ?? 0) + 1);
return map;
}, new Map());
const requiredArray = [...requiredMap.entries()];
const map = new Map();
const successRequired = () =>
requiredArray.every(([key, value]) => map.get(key) >= value);

let answer = "";
let start = 0;

for (let i = 0; i < s.length; i++) {
if (requiredMap.has(s[i])) map.set(s[i], (map.get(s[i]) ?? 0) + 1);

while (successRequired()) {
const now = s.slice(start, i + 1);
answer = answer === "" || answer.length >= now.length ? now : answer;

if (map.has(s[start])) {
map.set(s[start], map.get(s[start]) - 1);
if (map.get(s[start]) === -1) map.delete(s[start]);
}

start++;
}
}

return answer;
};
74 changes: 74 additions & 0 deletions pacific-atlantic-water-flow/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @description
* brainstorming:
* bfs + memoization
*
* n = length of height
* m = length of height[i]
* time complexity: O(n*m * 4^n*m)
Copy link
Contributor

Choose a reason for hiding this comment

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

상하좌우에 대한 4방향 접근으로 인해 4^n*m으로 계산하신걸까요?
visited 를 사용해서 memoization 하니 각 방향이n*m만큼 탐색일까 하는 의문이 듭니다!
혹시 가능하시다면 시간 복잡도 계산 과정 설명 부탁드립니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

안녕하세요. @wogha95 님! 리뷰 코멘트가 늦어진점 죄송합니다🥲

코멘트에 대한 리뷰는 다음과 같아요!
pacific이며 atlantic인 경우에만 memization이 되도록 구현했어요.
그래서 각 인덱스마다 접근시 memization이 안되는 경우가 존재하며 최악의 상황의 시간복잡도는 O(nm * 4^nm) 으로 계산했어요.
추가로 visited는 전역에서 사용하는 변수이지만 해당 bfs 스코프에서 다룰수 있게 값을 설정하여 매번 4방향을 탐색하도록 동작하도록 구현했어요.
그래서 제가 계산한 시간복잡도는 O(nm * 4^nm) 인데 이해가 됐을까요?

* space complexity: O(n*m)
*/
var pacificAtlantic = function (heights) {
const visited = Array.from({ length: heights.length }, (_, i) =>
Array.from({ length: heights[i].length }, () => false)
);
const memo = new Map();

const bfs = (row, column) => {
const dr = [0, 0, -1, 1];
const dc = [1, -1, 0, 0];
const queue = [[row, column]];
let [pacific, atlantic] = [false, false];
let queueIndex = 0;

while (queueIndex !== queue.length) {
const currentLastLength = queue.length;

while (queueIndex !== currentLastLength) {
const [r, c] = queue[queueIndex++];
visited[r][c] = `${row},${column}`;

if (memo.has(`${r},${c}`)) {
memo.set(`${row},${column}`, [row, column]);
return;
}

for (let i = 0; i < 4; i++) {
const nextR = r + dr[i];
const nextC = c + dc[i];
const isPacific = nextR === -1 || nextC === -1;
const isAtlantic =
nextR === heights.length || nextC === heights[0].length;

if (isPacific) {
pacific = true;
continue;
}
if (isAtlantic) {
atlantic = true;
continue;
}

if (visited[nextR][nextC] === `${row},${column}`) continue;

if (heights[r][c] < heights[nextR][nextC]) continue;

queue.push([nextR, nextC]);
}
}

if (pacific && atlantic) {
memo.set(`${row},${column}`, [row, column]);
return;
}
}
};

for (let row = 0; row < heights.length; row++) {
for (let column = 0; column < heights[row].length; column++) {
bfs(row, column);
}
}

return [...memo.values()];
};