738.单调递增的数字
文章
思路
把数字按十进制位顺序存到数组中,从最高位开始检查是否存在递减区间
当检查到递减时,将递减区间左端点的值减一,左端点右侧的所有值置为9
从这个左端点开始向左检查是否满足向左递减,如果不满足则将当前位置值置为9,其左的值减一
结束后计算数组对应的数字
代码
class Solution {
public int monotoneIncreasingDigits(int n) {
if (n < 10) {
return n;
}
List<Integer> nums = new ArrayList<>();
while (n > 0) {
nums.add(n % 10);
n /= 10;
}
n = nums.size();
int i, j, res;
i = n - 1;
res = 0;
while (i > -1) {
if (i == 0 || nums.get(i) <= nums.get(i - 1)) {
--i;
} else {
j = i - 1;
while (j > -1) {
nums.set(j, 9);
--j;
}
nums.set(i, nums.get(i) - 1);
++i;
while (i < n) {
if (nums.get(i) > nums.get(i - 1)) {
nums.set(i - 1, 9);
nums.set(i, nums.get(i) - 1);
}
++i;
}
break;
}
}
i = n - 1;
while (i > -1){
res *= 10;
res += nums.get(i);
--i;
}
return res;
}
}
968.监控二叉树
文章
思路
没有思路,求助卡哥
卡哥思路是贪心
1)局部最优:让叶子节点的父节点安装摄像头;全局最优:摄像头总数最少
2)后续遍历过程中隔两个节点放一个摄像头
分别用3个整数表示三个状态,比如-1:没覆盖,0:覆盖但不安装摄像头,1:安装摄像头
1)如果节点为null,则视为0
2)如果两个子节点都返回0,则表示当前节点没被覆盖,返回-1
3)如果两个子节点中有一个返回-1,则当前节点必安装摄像头返回1
4)如果两个子节点中有一个返回1,则当前节点必被覆盖,为0或1,而1的情况在3)中考虑过了,所以此时只要返回0
最后要注意根节点的状态,如果根节点返回值是-1或0,就需要单独给根节点安装摄像头
代码
class Solution {
private int result;
public int minCameraCover(TreeNode root) {
result = 0;
if (dfs(root) == -1) {
++result;
}
return result;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int l = dfs(node.left);
int r = dfs(node.right);
if (l == 0 && r == 0) {
return -1;
} else if (l == -1 || r == -1) {
++result;
return 1;
} else if (l == 1 || r == 1) {
return 0;
} else {
return 0;
}
}
}
总结
今天题少,多休息