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

2023-12-23 18:23:46

判断区间是否重叠(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;
    }

文章来源:https://blog.csdn.net/weixin_45765073/article/details/135167173
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。