中级农民
- 积分
- 115
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-12-7
- 最后登录
- 1970-1-1
|
8月16日 刷题第十六天 打卡16天
-加油!
今天3道题
1. Find target successor at BST
-就是一个简单的inorder Traversal
-然后用一个boolean flag来记录有没有找到target
-如果找到target,那么下一个就是要找的元素
-如果target之后没有元素了,那么就返回-1;
2.All subsetsII(DFS升级版) -> 有重叠,无序的string
-转化成有序的array
-然后需要一个list,还需要一个set
-最后DFS处理的时候先处理第一次遇到的char,慢点遇到以后就
-直接去重
3.Leetcode 333 largest BST subtree(时间复杂度要求O(n))
High level:
Use recursion, and use a helper function and find left hand side largest BST subTree
and rightHandside largest BST subTree;
Besides, if root.value larger than the max value of left BST subTree and root.value smaller than min value of rightBST subTree ->
then this root itself can form a larger BST with both left and right BST;
Small trick here, use a int[] array to store the current minValue, maxValue and current longest BST subtree.
Details:
base case:
if (root == null) {
return {Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
}
recursive rule
int[] left = helper(root.left);
int[] right = helper(root.right);
//initialize a new array;
int[] newArray = new int[3];
case 1:(root can be added to form a larger BST)
//if (root.key > left[1] && root.key < right[0]) {
update current new array;
}
case 2:(otherwise)
// update the only new Array[2] -> max(left[2], right[2]);
//总结:O(n)的时间复杂度的做法结合recursion已经想到了;
//也考虑到使用int[] globalMax来记录最长的BST
//也考虑到使用int[] minAndMax用来表示当前的最大最小值
//关键是helper function当中的分左右情况没有考虑清楚,然后recursive rule 分析得太复杂了
//提炼一下:
//用一个int[] array当中带三个参数表达当前的最小值,最大值和最长BST节点个数
//在recursive rule里面,
//Step1: 分别建立属于left, right的两个arrays
//然后从helper function处拿到返回值
//Step2:
//建立当前的new Array,并去根据具体cases来分析并update
//case1(root 可以并做更大的subTree)
//case2(otherwise)
//返回当前的new Array
今日份的刷题就到这里,如果觉得对你也有参考价值,请点赞,加米,握手三连!谢谢!加油加油! |
|