贪心算法高频问题-区间问题

判断区间是否重叠(Leetcode 252)

public static boolean canAttendMeetings(int[][] intervals) {
        //按照会议开始时间排序
        Arrays.sort(intervals, (a, b) ->  a[0] - b[0]);
        for (int i = 0; i < intervals.length - 1; i++) {
            if (intervals[i + 1][0] <= intervals[i][1]) {
                return false;
            }
        }
        return true;
    }

插入区间(LeetCode 57)

/**
     * 先把结尾处小于新增区间初始的加入到ans
     * 对重复/新增区间做判断
     * 把开始点大于上一节点后的节点加入到ans
     * @param intervals
     * @param newInterval
     * @return
     */
    public static int[][] insert(int[][] intervals, int[] newInterval) {
        int[][] ans = new int[intervals.length + 1][2];
        int t = 0;
        int i = 0;
        // 先把结尾处小于新增区间初始的加入到ans
        while (i < intervals.length && intervals[i][1] < newInterval[0]) {
            ans[t++] = intervals[i++];
        }
        // 对重复/新增区间做判断
        while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
            newInterval[0] = Math.min(intervals[i][0], newInterval[0]);
            newInterval[1] = Math.max(intervals[i++][1], newInterval[1]);
        }
        ans[t++] = newInterval;
        // 把开始点大于上一节点后的节点加入到ans
        while (i < intervals.length && intervals[i][0] > newInterval[1]) {
            ans[t++] = intervals[i++];
        }
        return Arrays.copyOf(ans, t);
    }

字符串分割(LeetCode 763)

public static List<Integer> partitionLabels(String S) {
        List<Integer> list = new LinkedList<>();
        char[] chars = S.toCharArray();
        int[] edges = new int[26];
        for (int i = 0; i < chars.length; i++){
            edges[chars[i] - 'a'] = i;
        }
        int index = 0, pre = -1;
        for (int i = 0; i < chars.length; i++) {
            index = Math.max(index, edges[chars[i] - 'a']);
            if (i == index) {
                list.add(i - pre);
                pre = i;
            }
        }
        return list;
    }

加油站问题(LeetCode 134)

public static int canCompleteCircuit(int[] gas, int[] cost) {
        int totNum = 0;
        int curNum = 0;
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            curNum += gas[i] - cost[i];
            totNum += gas[i] - cost[i];
            if (curNum < 0) {
                curNum = 0;
                start = i + 1;
            }
        }
        if (totNum < 0) {
            return -1;
        }
        return start;
    }

你可能感兴趣的:(数据结构与算法,贪心算法,算法)