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

435. 无重叠区间 Non-overlapping Intervals - LeetCode

interval的题做过很多次,面试也遇到过几次,竟然是贪心么

1.排序

if (nums.length == 0) return 0;

sort(nums);

for (int i = 1; i < nums.length; i++)

        if (nums[i][0] < nums[i - 1][1])

                count++;

                nums[i][1] = Math.min(nums[i][1], nums[i - 1][1]);

return count;

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        if (intervals.length == 0) return 0;
        Arrays.sort(intervals, (a, b) -> 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][1], intervals[i][1]);
            }
        }
        return count;
    }
}

763.划分字母区间 Partition Labels - LeetCode

1.记录每个元素最远出现位置,

2. 根据最远出现位置确定分界线

int[] hash = new int[27]

for (int i = 0; i < s.length; i++)

        s[i] - 'a' = i;

 int[] res;

int left = 0;

int right = 0;

for (i = 0; i < s.length(); i++)

        right = max(right, hash[i] - 'a');

        if (i == right)

                res.add(right - left + 1);

                left = i + 1;

return res;

class Solution {
    public List partitionLabels(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a'] = i; 
        }

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

 56. 合并区间 Merge Intervals - LeetCode

class Solution {
    public int[][] merge(int[][] intervals) {
        List list = new ArrayList<>();
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);

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

        int[][] res = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }

        return res;
    }
}

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