本文主要是介绍【代码随想录——贪心算法——四周目】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.用最少数量的箭引爆气球
func findMinArrowShots(points [][]int) int {n := len(points)sort.Slice(points, func(i, j int) bool {if points[i][0] != points[j][0] {return points[i][0] < points[j][0]} else {return points[i][1] < points[j][1]}})cover := points[0][1]count := 1for i := 0; i<n; i++ {if points[i][1] <= cover {//缩小的cover范围cover = points[i][1]}if points[i][0] <= cover { //代表这只箭还能射中continue}count++cover = points[i][1]}return count
}
2.无重叠区域
func eraseOverlapIntervals(intervals [][]int) int {n := len(intervals)sort.Slice(intervals, func(i, j int) bool {if intervals[i][0] != intervals[j][0] {return intervals[i][0] < intervals[j][0]} else {return intervals[i][1] < intervals[j][1]}})cover := intervals[0][1]res := 0for i := 1; i < n; i++ {if intervals[i][0] < cover { //表明存在交叉res++if intervals[i][1] < cover { //存在提早结束的选项cover = intervals[i][1]}} else { //不存在交叉cover = intervals[i][1]}}return res
}
3.划分字母区间
func partitionLabels(s string) []int {var res []intvar marks [26]intsize,left,right := len(s),0,0for i:=0; i<size; i++{//每个字母最远出现的位置marks[s[i]-'a'] = i}for i:=0; i<size; i++{right = max(right,marks[s[i]-'a'])if i == right {res = append(res,right - left + 1)left = i + 1}}return res
}func max(a,b int) int{if a < b {return b}return a
}
4.合并区间
func merge(intervals [][]int) [][]int {res := make([][]int, 0)sort.Slice(intervals, func(i, j int) bool {if intervals[i][0] != intervals[j][0] {return intervals[i][0] < intervals[j][0]} else {return intervals[i][1] < intervals[j][1]}})n, left, right := len(intervals), intervals[0][0], intervals[0][1]for i := 1; i < n; i++ {if intervals[i][0] <= right { //可能需要更新rightif intervals[i][1] > right {right = intervals[i][1]}} else {res = append(res, []int{left, right})left = intervals[i][0]right = intervals[i][1]}}res = append(res, []int{left, right})return res
}
5.单调递增的数字
func monotoneIncreasingDigits(n int) int {len := 0nums := make([]int, 11)for n != 0 {nums[len] = n % 10n = n / 10len++}for i := 0; i < len; i++ {if nums[i] < nums[i+1] {nums[i+1]--for j := i; j >= 0; j-- {nums[j] = 9}}}res := 0for i := len - 1; i >= 0; i-- {res = res*10 + nums[i]}return res
}
6.监控二叉树
思路:后序遍历,从底到上,节点有三种状态。
var (count int
)func minCameraCover(root *TreeNode) int {count = 0if traversal(root) == 0 {count++}return count
}/*
*
0:该节点无覆盖
1:本节点有摄像头
2:本节点有覆盖
*
*/
func traversal(root *TreeNode) int {if root == nil {return 2}left := traversal(root.Left)right := traversal(root.Right)if left == 0 && right == 0 {count++return 1} else if left == 0 && (right == 1 || right == 2) {count++return 1} else if (left == 1 || left == 2) && right == 0 {count++return 1} else if left == 2 && right == 2 {return 0} else {return 2}
}
这篇关于【代码随想录——贪心算法——四周目】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!