【代码随想录Day35】贪心算法

435 无重叠区间

https://leetcode.cn/problems/non-overlapping-intervals/ 跟昨天打气球一模一样除了输出时是intervals.length - count而不是count,都是求不相交interval个数。

 求最大不相交interval个数
class Solution {  //方法一,按右边界排序,重合的去掉, 思考,为什么当结束点相同时可以随意排序
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
        int count = 1;
        int lastEnd = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] < lastEnd) continue;
            count++;
            lastEnd = intervals[i][1];
        }
        return intervals.length - count;
    }
}
class Solution {  //方法二,按左边界排序,有重合的右端合并成交集(可以理解成相交的第二个interval不count了)
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        int count = 1;
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] < intervals[i - 1][1]) {
                intervals[i][1] = Math.min(intervals[i][1], intervals[i - 1][1]);
                continue;
            }
            count++;
        }
        return intervals.length - count;
    }
}

763 划分字母区间

https://leetcode.cn/problems/partition-labels/

麻烦的思路一:存in[26][2],遍历找出26字母的区间,再合并区间,数合并后共多少个区间。

巧妙的思路二:遍历存int[26]是字母最远的index,遍历更新当前区间需要切割的最远距离,当最远距离为自己时切。


class Solution { //思路二
    public List partitionLabels(String s) {
        int[] lastPositon = new int[26];
        for (int i = 0; i < s.length(); i++) {
            lastPositon[s.charAt(i) - 'a'] = i;
        }
        int count = 0;
        int needToInclude = 0;
        List result = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            needToInclude = Math.max(needToInclude, lastPositon[s.charAt(i) - 'a']);
            count++;
            if (needToInclude == i) {
                result.add(count);
                count = 0;
            }
        }
        return result;
    }
}

56 合并区间

https://leetcode.cn/problems/merge-intervals/

左端点排序,从左到右遍历,边遍历边合并去union,注意最后一个interval需要循环外加上。

class Solution { 
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        List result = new ArrayList<>();
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] > intervals[i - 1][1]) {
                result.add(intervals[i - 1]);
            } else {
                //intervals[i][0] = intervals[i - 1][0];      排序已经保证了,不需要这行
                intervals[i][1] = Math.max(intervals[i - 1][1], intervals[i][1]);  // bug合并后右端点大小不确定需要比较大小。
            }
        }
        result.add(intervals[intervals.length -1]);
        return result.toArray(new int[result.size()][]);  // bug 不是new int[][result.size()]
    }
}

你可能感兴趣的:(代码随想录,算法,leetcode,贪心算法)