Skip to content

Commit 5f0a5ac

Browse files
committed
Add week 04 solutions for merge, max depth, find min
1 parent c2bba21 commit 5f0a5ac

3 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int findMin(int[] nums) {
3+
int left = 0;
4+
int right = nums.length - 1;
5+
6+
while (left < right) {
7+
int mid = left + (right - left) / 2;
8+
9+
if (nums[mid] > nums[right]) {
10+
left = mid + 1;
11+
} else {
12+
right = mid;
13+
}
14+
}
15+
16+
return nums[left];
17+
}
18+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
private int max;
3+
4+
public int maxDepth(TreeNode root) {
5+
if (root == null) {
6+
return 0;
7+
}
8+
9+
max = 0;
10+
dfs(root, 1);
11+
12+
return max;
13+
}
14+
15+
private void dfs(TreeNode node, int depth) {
16+
if (node == null) {
17+
return;
18+
}
19+
20+
max = Math.max(max, depth);
21+
22+
dfs(node.left, depth + 1);
23+
dfs(node.right, depth + 1);
24+
}
25+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
3+
ListNode dummy = new ListNode();
4+
ListNode tail = dummy;
5+
6+
while (list1 != null && list2 != null) {
7+
if (list1.val <= list2.val) {
8+
tail.next = new ListNode(list1.val);
9+
list1 = list1.next;
10+
} else {
11+
tail.next = new ListNode(list2.val);
12+
list2 = list2.next;
13+
}
14+
15+
tail = tail.next;
16+
}
17+
18+
while (list1 != null) {
19+
tail.next = new ListNode(list1.val);
20+
tail = tail.next;
21+
list1 = list1.next;
22+
}
23+
24+
while (list2 != null) {
25+
tail.next = new ListNode(list2.val);
26+
tail = tail.next;
27+
list2 = list2.next;
28+
}
29+
30+
return dummy.next;
31+
}
32+
}

0 commit comments

Comments
 (0)