算法训练营day35

1.435无重叠区间
class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        int n = intervals.length;
        if (n == 0) return 0;
            // 按 end 升序排序
            Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
            // 至少有一个区间不相交
            int count = 1;
            // 排序后,第一个区间就是 x
            int x_end = intervals[0][1];
            for (int[] interval : intervals) {
                int start = interval[0];
                if (start >= x_end) {
                    // 找到下一个选择的区间了
                    count++;
                    x_end = interval[1];
                }
            }
            //count为最多的互不相交的区间,n - count就为最少的需要去除的区间数量
            count = n - count;
            return count;
            }
}
2.划分字母区间
class Solution {
    public List<Integer> partitionLabels(String s) {
    //使用HashMap记录每个字符出现的最大索引值
        Map<Character, Integer> map = new HashMap<>();
        // filling impact of character's
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            map.put(ch, i);
        }
        // making of result
        List<Integer> res = new ArrayList<>();
        int prev = -1;
        int max = 0;
        
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i); //ch是当前遍历的字符
        //取出当前字符出现的最大索引和max中的最大值
            max = Math.max(max, map.get(ch));
//遍历到最大值,表示i之前的所有不同种类字符都被包含了,否则 max > i,表示还存在字符没有被遍历完
            if(max == i){
        // partition time,将长度返回,并更新起始位置prev
                res.add(max - prev);
                prev = max;
            }
        }
        return res;
    }
}
3.合并区间
class Solution {
    public int[][] merge(int[][] intervals) {
    if(intervals == null || intervals.length == 0) return new int[][]{};
    // 按区间的 start 升序排列
    Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
    List<int[]> res = new ArrayList<>();
    //将第一个元素加入到res中
    res.add(intervals[0]);
    
    // 注意从1开始
    for(int i=1; i<intervals.length; i++){
        int[] curr = intervals[i];
        // res 中最后一个元素的引用
        int[] last = res.get(res.size()-1);
        if(curr[0] <= last[1]){ //当前的起始 < 上一个结束,表示相交
            // 找到最大的 end
            last[1] = Math.max(last[1], curr[1]);
        } else{ //否则不相交
            // 处理下一个待合并区间
            res.add(curr);
        }
    }
    return res.toArray(new int[res.size()][]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值