夸父追日:第八章 贪心算法 part05

今日收获:合并区间,单调递增的数字,监控二叉树

1. 合并区间

题目链接:56. - 力扣(LeetCode)

思路:

(1)局部最优:将区间靠左排序,每次合并都取最大的右区间。

(2)记录初始的左右区间,如果遍历到重叠区间,更新右区间为重叠区间中最长的右区间;如果没有重叠,就添加重叠区间的起始位置到结果中,再更新起始位置为当前区间的起始位置。注意遍历结束后需要再添加一次区间的起始位置。

方法:

java 复制代码
class Solution {
    public int[][] merge(int[][] intervals) {
        // 向左排序
        Arrays.sort(intervals,(a,b)->Integer.compare(a[0],b[0]));

        List<int[]> result=new ArrayList<>();
        int left=intervals[0][0];
        int rightMostBound=intervals[0][1];
        for (int i=1;i<intervals.length;i++){
            // 重叠区间
            if (intervals[i][0]<=rightMostBound){
                rightMostBound=Math.max(intervals[i][1],rightMostBound);  // 扩展重叠区间
            }else{  // 不重叠
                result.add(new int[]{left,rightMostBound});
                left=intervals[i][0];
                rightMostBound=intervals[i][1];
            }
        }
        result.add(new int[]{left,rightMostBound});
        return result.toArray(new int[result.size()][]);
    }
}

总结:自己的代码能力还是不够,有的时候思路大体对了,但是代码中有很多的小错误。

2. 单调递增的数字

题目链接:738. - 力扣(LeetCode)

思路:

(1)局部最优:如果发现前后两位不满足顺序要求,就将前一位减一,后一位取9

(2)从后往前遍历数字,如果后一位大于前一位,就更新变为9的位置,前一位减一。利用flag记录变为9的位置是为了"1000"这样的用例。

方法:

java 复制代码
class Solution {
    public int monotoneIncreasingDigits(int n) {
        String str=String.valueOf(n);
        char[] chars=str.toCharArray();
        
        int len=chars.length;
        int flag=len;  // 变为9的位置

        // 从后向前遍历
        for (int i=len-1;i>0;i--){
            if (chars[i-1]>chars[i]){
                chars[i-1]--;
                flag=i;
            }
        }

        // 赋值为9
        for (int i=flag;i<len;i++){
            chars[i]='9';
        }

        return Integer.parseInt(new String(chars));
    }
}

总结:int类型转换为String类型,方法String.valueOf(n),需要总结到String常用方法中

3. 监控二叉树

题目链接:968. - 力扣(LeetCode)

思路:从下往上遍历,在叶子节点的父节点上放摄像头,然后再每隔两个节点放一个摄像头,这样可以省下更多的摄像头。

二刷一定可以啃下来!

相关推荐
这个DBA有点耶1 小时前
SQL调优进阶:从“优化一条SQL”到“优化一个系统”的思维升级
java·大数据·数据库·sql·程序人生·dba·改行学it
csdn2015_2 小时前
springboot读取配置的方法
java·spring boot·spring
AOwhisky3 小时前
下一代容器来了?Docker 宣布原生支持 WebAssembly
java·运维·docker·容器·rust·wasm
QXWZ_IA3 小时前
1库1图1批是什么?千寻位置公安地图数据体系详解
科技·算法·能源·媒体·交通物流·政务
c238564 小时前
Bug 猎手入门指南
c++·算法·bug
Reart4 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
云云只是个程序马喽4 小时前
海外短剧平台搭建方案:私有化源码系统选型|云微短剧系统技术架构拆解
java·php
Reart5 小时前
Leetcode 198.打家劫舍(716)
后端·算法
Jerry5 小时前
LeetCode 110. 平衡二叉树
算法