代码随想录算法训练营第三十六天 | 435. 无重叠区间 | 763. 划分字母区间 | 56. 合并区间

435. 无重叠区间

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals,(a,b) -> {
            return Integer.compare(a[0],b[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. 划分字母区间

class Solution {
    public List partitionLabels(String s) {
        List list = new LinkedList<>();
        int[] edge = new int[26];
        char[] chars = s.toCharArray();
        //记录s中每个字母的最后一个的位置
        for(int i = 0; i < chars.length; i++){
            edge[chars[i] - 'a'] = i;
        }

        int left= 0,right = 0;
        for(int i = 0; i < chars.length; i++){
            right = Math.max(right, edge[chars[i] - 'a']);
            if (i == right) {
                list.add(right - left + 1);
                left = i + 1;
            }
        }
        return list;
    }
}

56. 合并区间

class Solution {
    public int[][] merge(int[][] intervals) {
        LinkedList res = new LinkedList<>();
        Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[0], o2[0]));
        res.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= res.getLast()[1]) {
                int start = res.getLast()[0];
                int end = Math.max(intervals[i][1], res.getLast()[1]);
                res.removeLast();
                res.add(new int[]{start, end});
            }else {
                res.add(intervals[i]);
            }         
        }
        return res.toArray(new int[res.size()][]);
    }
}

你可能感兴趣的:(算法,leetcode,c++)