Skip to content

Commit b8c50cc

Browse files
authored
[j2h30728] WEEK 04 Solutions (#2760)
* week4: 104. Maximum Depth of Binary tree * week4: 21. Merge Two Sorted Lists * week4: 153. Find Minimum in Rotated Sorted Array * week4: 322. Coin Change * fix: add trailing newline to week4 solution files
1 parent 46d6ee8 commit b8c50cc

4 files changed

Lines changed: 75 additions & 0 deletions

File tree

coin-change/j2h30728.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function coinChange(coins: number[], amount: number): number {
2+
const dp = new Array(amount + 1).fill(amount + 1);
3+
dp[0] = 0;
4+
5+
for (let i = 1; i <= amount; i++) {
6+
for (const coin of coins) {
7+
if (i - coin >= 0) {
8+
dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
9+
}
10+
}
11+
}
12+
13+
return dp[amount] > amount ? -1 : dp[amount];
14+
};
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
function findMin(nums: number[]): number {
2+
const n = nums.length - 1;
3+
let last = nums[n];
4+
let left = 0, right = n;
5+
6+
while(left < right){
7+
const mid = (left + right) >> 1;
8+
if(nums[mid] > last) left = mid + 1;
9+
else right = mid;
10+
}
11+
return nums[left];
12+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
15+
function maxDepth(root: TreeNode | null): number {
16+
if(!root) return 0;
17+
const maxLeft = maxDepth(root.left);
18+
const maxRight = maxDepth(root.right);
19+
return Math.max(maxLeft, maxRight) + 1;
20+
};

merge-two-sorted-lists/j2h30728.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
14+
const root = new ListNode();
15+
let tail = root;
16+
17+
while(list1 !== null && list2 !== null){
18+
if(list1.val <= list2.val){
19+
tail.next = list1;
20+
list1 = list1.next;
21+
}else{
22+
tail.next = list2;
23+
list2 = list2.next;
24+
}
25+
tail = tail.next;
26+
}
27+
tail.next = list1 !== null ? list1 : list2;
28+
return root.next;
29+
};

0 commit comments

Comments
 (0)