Skip to content

Commit

Permalink
Merge pull request #570 from gitsunmin/main
Browse files Browse the repository at this point in the history
[gitsunmin] Week12 Solutions
  • Loading branch information
SamTheKorean authored Nov 3, 2024
2 parents bcc02f2 + 648f6b2 commit c8d452b
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
18 changes: 18 additions & 0 deletions merge-intervals/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* https://leetcode.com/problems/merge-intervals/
* time complexity : O(n)
* space complexity : O(n)
*/

function merge(intervals: number[][]): number[][] {
if (intervals.length === 0) return [];

intervals.sort((a, b) => a[0] - b[0]);

const merged: number[][] = [];
for (const interval of intervals) {
if (merged.length === 0 || merged[merged.length - 1][1] < interval[0]) merged.push(interval);
else merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
}
return merged;
};
33 changes: 33 additions & 0 deletions remove-nth-node-from-end-of-list/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/
* time complexity : O(n)
* space complexity : O(1)
*/

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)
}
}

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
const dummy = new ListNode(0, head);
let first: ListNode | null = dummy;
let second: ListNode | null = dummy;

for (let i = 0; i <= n; i++) {
if (first !== null) first = first.next;
}

while (first !== null) {
first = first.next;
second = second!.next;
}

if (second !== null && second.next !== null) second.next = second.next.next;

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

class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}

function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (p === null && q === null) return true;
if (p === null || q === null) return false;
if (p.val !== q.val) return false;

return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

0 comments on commit c8d452b

Please sign in to comment.