738.单调递增的数字
当前一位比后一位大的时候,前一位-1, 后面所有位均变为9才可以
func monotoneIncreasingDigits(n int) int {
input := make([]int, 0)
for n >0{
input = append(input, n % 10)
n /= 10
}
left := 0
right := len(input) - 1
for left < right{
tmp := input[right]
input[right] = input[left]
input[left] = tmp
right--
left++
}
sum := 0
for i := len(input) - 1; i > 0; i--{
if input[i] < input[i - 1]{
input[i - 1] -= 1
for j := i; j < len(input); j++{
input[j] = 9
}
}
}
for i := 0; i < len(input); i++{
sum *= 10
sum += input[i]
}
return sum
}
968.监控二叉树
一共有三种状态,0-当前节点安装监控。1-当前节点被覆盖。2-当前节点不被覆盖。
因为叶子节点必然大于等于根节点,所以从下往上开始遍历寻找。
将叶子节点的子节点设定为被覆盖,那么叶子节点就需要判定是否需要加装监控。
最后还需要判断根节点的状态。
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minCameraCover(root *TreeNode) int {
count := 0
var build func(*TreeNode)int
build = func(node *TreeNode)int{
if node== nil{
return 1
}
left := build(node.Left)
right := build(node.Right)
if left == 2 || right == 2{
count++
return 0
}
if left == 1 && right == 1{
return 2
}
return 1
}
if build(root) == 2{
count++
}
return count
}