Skip to content

[lhc0506] Week07 solutions #1480

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
27 changes: 27 additions & 0 deletions longest-substring-without-repeating-characters/lhc0506.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let maxLength = 0;
const charSet = new Set();

let start = 0, end = 0;

while (end < s.length) {
if (charSet.has(s[end])) {
charSet.delete(s[start]);
start += 1;
continue;
}

charSet.add(s[end]);
end += 1;
maxLength = Math.max(maxLength, end - start);
}

return maxLength;
};

// 시간복잡도: O(n)
// 공간복잡도: O(n)
42 changes: 42 additions & 0 deletions number-of-islands/lhc0506.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
const m = grid.length;
const n = grid[0].length;
const visited = Array.from(new Array(m), () => new Array(n).fill(false));
const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];

let islandCount = 0;

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1' && !visited[i][j]) {
const queue = [[i, j]];
visited[i][j] = true;

while (queue.length) {
const [y, x] = queue.shift();

for (const [dy, dx] of directions) {
const newY = y + dy;
const newX = x + dx;

if (newY >= 0 && newY < m && newX >= 0 && newX < n && grid[newY][newX] === '1' && !visited[newY][newX]) {
visited[newY][newX] = true;
queue.push([newY, newX]);
}
}
}

islandCount += 1;
}
}
}

return islandCount;
};

// 시간복잡도: O(m * n)
// 공간복잡도: O(m * n)
28 changes: 28 additions & 0 deletions reverse-linked-list/lhc0506.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let prevNode = null;
let currentNode = head;

while(currentNode) {
const nextNode = currentNode.next;
currentNode.next = prevNode;

prevNode = currentNode;
currentNode = nextNode;
}

return prevNode;
};

// 시간복잡도: O(n)
// 공간복잡도: O(1)