Mock Test: Microsoft #6
3812 ワード
Trim a Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
//end case
if (root == null) {
return root;
}
//val이 high보다 크면 오른쪽에 있는 것들은 다 현재 val보다도 클테니 냅다버리고 왼쪽으로 가야함
if (root.val > high) {
return trimBST(root.left, low, high);
}
//val이 low보다 작으면 왼쪽것들은 너무 작으니 냅다 오른쪽으로 감
if (root.val < low) {
return trimBST(root.right, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Trim a Binary Search Tree.Memory Usage: 38.5 MB, less than 84.74% of Java online submissions for Trim a Binary Search Tree.
この問題は以前聞いたことのある中間試験で出たことがありますが…^^
PTSDが来ました^^
Add Two Numbers II
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l1r = reverse(l1);
ListNode l2r = reverse(l2);
ListNode cur1 = l1r;
ListNode cur2 = l2r;
int carry = 0;
ListNode result = new ListNode(-1);
ListNode cur = result;
while (cur1 != null && cur2 != null) {
int val = carry + cur1.val + cur2.val;
carry = val / 10;
val = val % 10;
cur.next = new ListNode(val);
cur1 = cur1.next;
cur2 = cur2.next;
cur = cur.next;
}
while (cur1 != null) {
int val1 = carry + cur1.val;
carry = val1 / 10;
val1 = val1 % 10;
cur.next = new ListNode(val1);
cur = cur.next;
cur1 = cur1.next;
}
while (cur2 != null) {
int val2 = carry + cur2.val;
carry = val2 / 10;
val2 = val2 % 10;
cur.next = new ListNode(val2);
cur = cur.next;
cur2 = cur2.next;
}
if (carry != 0) {
cur.next = new ListNode(1);
}
return reverse(result.next);
}
private ListNode reverse(ListNode n) {
ListNode prev = null;
ListNode cur = n;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
n = prev;
return n;
}
}
Runtime: 2 ms, faster than 98.52% of Java online submissions for Add Two Numbers II.Memory Usage: 39 MB, less than 85.50% of Java online submissions for Add Two Numbers II.
Add Two Numbers IにはReverseのみ追加されています^^
Add Two数を無駄にしなくてよかった...そうですね^^...
Reference
この問題について(Mock Test: Microsoft #6), 我々は、より多くの情報をここで見つけました https://velog.io/@jwade/Mock-Test-Microsoft-6テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol