Day38.算法训练

435. 无重叠区间

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator() {
            @Override public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        int count = 0;
        if (intervals.length == 1) {
            return count;
        }
        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) {
        int[] map = new int[26];
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            map[chars[i] - 'a'] = i;
        }

        List res = new ArrayList<>();
        int left = 0;
        int right = 0;
        for (int i = 0; i < chars.length; i++) {
            right = Math.max(right, map[chars[i] - 'a']);
            if (i == right) {
                res.add(right - left + 1);
                left = i + 1;
            }
        }
        return res;
    }
}

56. 合并区间

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator() {
            @Override public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List res = new ArrayList<>();

        res.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= res.get(res.size() - 1)[1]) {
                res.get(res.size() - 1)[1] = Math.max(intervals[i][1], res.get(res.size() - 1)[1]);
            } else {
                res.add(intervals[i]);
            }
        }
        return res.toArray(new int[0][0]);
    }
}

你可能感兴趣的:(算法,java,开发语言)