【代码随想录Day30】贪心算法Part04

452. 用最少数量的箭引爆气球

题目链接/文章讲解:代码随想录

视频讲解:贪心算法,判断重叠区间问题 | LeetCode:452.用最少数量的箭引爆气球_哔哩哔哩_bilibili

java 复制代码
class Solution {
    public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[0], o2[0]);
            }
        });
        int count = 1;
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] > points[i - 1][1]) {
                count++;
            } else {
                points[i][1] = Math.min(points[i][1], points[i - 1][1]);
            }
        }
        return count;
    }
}

435. 无重叠区间

题目链接/文章讲解:代码随想录

视频讲解:贪心算法,依然是判断重叠区间 | LeetCode:435.无重叠区间_哔哩哔哩_bilibili

java 复制代码
class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[0], o2[0]);
            }
        });
        int count = 0;
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] < intervals[i - 1][1]) {
                count++;
                intervals[i][1] = Math.min(intervals[i][1], intervals[i - 1][1]);
            }
        }
        return count;
    }
}

763.划分字母区间

题目链接/文章讲解:代码随想录

视频讲解:贪心算法,寻找最远的出现位置! LeetCode:763.划分字母区间_哔哩哔哩_bilibili

java 复制代码
class Solution {
    public List<Integer> partitionLabels(String s) {
        int[] last = new int[26];
        char[] charArray = s.toCharArray();

        // 记录每个字符最后出现的位置
        for (int i = 0; i < charArray.length; i++) {
            last[charArray[i] - 'a'] = i;
        }

        List<Integer> list = new ArrayList<>();
        int start = 0;
        int end = 0;

        for (int i = 0; i < charArray.length; i++) {
            // 更新当前分区的结束位置
            end = Math.max(end, last[charArray[i] - 'a']);

            // 如果当前位置是分区的结束位置,则记录分区长度并更新 start
            if (i == end) {
                list.add(end - start + 1);
                start = end + 1;
            }
        }

        return list;
    }
}
相关推荐
简 洁 冬冬18 分钟前
泛型方法写法全面辨析:从「能编译」到「能跑」到「能用」
java·泛型
YLCHUP27 分钟前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
LGL6030A33 分钟前
Java学习历程31——初识Spring Boot
java·spring boot·学习
思麟呀1 小时前
背包DP(01背包+完全背包)
c++·算法
笑容掩饰我的失落2 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Lansonli3 小时前
大数据Spark(八十八):Spark任务资源之Standalone集群测试
java·服务器·spark
budingxiaomoli3 小时前
Spring AOP
java·spring·java-ee
特立独行的猫A3 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
Pniubi3 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
nice_lcj5203 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru