今天芝加哥虽然很冷,但阳光明媚,是个刷题的好日子。
昨天晚上跟孔神一番交流后感受到了巨大差距,无论是java基础,算法基础,system design基础,项目经验还是努力程度,差距都是全方位的,想到自己一直以来都缺乏毅力,不能做到有始有终,也经常被老爸和suki诟病。
所以从今天起我准备每天都至少刷五道题,熟练后增加,立帖为证,自我激励,往者不可谏,来者犹可追。
祝愿自己能在接下来的几个月里找到满意的工作。
废话不多说,开始写题:
Stack:
- min stack
maintain two stacks, s1 is to store all push(), s2 is to store min values(every push() in one correspond to a min value in two)
private Deques1;
private Deques2;
public MinStack() {
s1 = new LinkedList();
s2 = new LinkedList();
}
- implement queue using stacks
maintain move() to complete moving from s1 to s2.
public void move(){
if (s1.isEmpty()) {
return;
}
if(s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.offerFirst(s1.pollFirst());
}
}
}
- Evaluate Reverse Polish Notation med
using a stack, when meeting string .equals() operators, pop the top two int in stack
note: string to int Integer.parseInt()
stack.offerFirst(Integer.parseInt(tk));
Binary Tree
Balanced Binary Tree
recursively get every node's height, to the left and right subTrees should follow abs(left - right) < 1
getHeight()
subProblem: root.left & root.right 's height
base case: root == null return 0
isBalanced()
if Math.abs(leftHeight, rightHeight) > 1 false
we say, to every node
subPro: isBalanced(root.left) && isBalanced(root.right)Symmetric Tree
need to prove that the left subtree and the right subtree are symmetric
subproblem:
isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left)
corner case:
if (left == null || right == null) {
return left == null && right == null;
}
if (left.val != right.val) {
return false;
}
- Same Tree
base case & subproblem
if (p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
98 valid BST
method1: inorder traverse the tree and when print new node, compare with the previous one.
method2: root.left subtree range (min, root)
root.right (root, max)
if (root.val <= min || root.val >= max) {
return false;
}
return isBST(root.left, min, root.val) && isBST(root.right, root.val, max);
Extra problem: Get Keys In Binary Search Tree In Given Range
在inorder in recursive way框架基础上加限制条件来剪枝
Maximum Depth of Binary Tree
同110 利用height() 求出左右子树高度比较即可Minimum Depth of Binary Tree
当没有左子树或者右子树时, 得分开判断
if (root.left != null && root.right != null)
return Math.min(minDepth(root.left), minDepth(root.right))+1;
else
return Math.max(minDepth(root.left), minDepth(root.right))+1;
}