差分数组

题目 难度 要点
拼车 不需要构造原始数组,直接判断即可
航班预定统计 构造原始数组
区间加法 构造原始数组
差分数组中,diff[i] 就是 nums[i] 和 nums[i-1] 之差;diff[0] = nums[0];

拼车

class Solution {

    public boolean carPooling(int[][] trips, int capacity) {
        Diff diff = new Diff(1001);
        for (int[] trip: trips) {
            diff.inc(trip[0], trip[1], trip[2]);
        }
        return diff.check(capacity);
    }

}

class Diff {

    private int size;

    private int[] diff;

    public Diff(int size) {
        this.size = size;
        this.diff = new int[size];
    }

    public void inc(int val, int start, int end) {
        diff[start] += val;
        diff[end] -= val;
    }

    public boolean check(int capacity) {
        int sum = diff[0];
        for (int i = 1; i < diff.length; i++) {
            if (sum > capacity) {
                return false;
            }
            sum += diff[i];
        }
        return sum <= capacity;
    }

}

航班预定统计

class Solution {
    public int[] corpFlightBookings(int[][] bookings, int n) {
        Diff diff = new Diff(n);
        for (int[] booking: bookings) {
            diff.inc(booking[2], booking[0] - 1, booking[1] - 1);
        }
        return diff.revert();
    }
}


class Diff {

    private int size;

    private int[] diff;

    public Diff(int size) {
        this.size = size;
        this.diff = new int[size];
    }

    public void inc(int val, int start, int end) {
        diff[start] += val;
        if (end + 1 < diff.length) {
                diff[end + 1] -= val;
            }
    }

    public int[] revert() {
        int[] sum = new int[diff.length];
        sum[0] = diff[0];
        for (int i = 1; i < diff.length; i++) {
            sum[i] = sum[i - 1] + diff[i];
        }
        return sum;
    }
}

区间加法

class Solution {
    public int[] getModifiedArray(int length, int[][] updates) {
        Diff diff = new Diff(length);
        for (int[] update: updates) {
            diff.inc(update[0], update[1], update[2]);
        }
        return diff.revert();
    }
}

class Diff {

    private int size;

    private int[] diff;

    public Diff(int size) {
        this.size = size;
        this.diff = new int[size];
    }

    public void inc(int start, int end, int val) {
        diff[start] += val;
        if (end + 1 < diff.length) {
            diff[end + 1] -= val;
        }
    }

    public int[] revert() {
        int[] sum = new int[diff.length];
        sum[0] = diff[0];
        for (int i = 1; i < diff.length; i++) {
            sum[i] = sum[i - 1] + diff[i];
        }
        return sum;
    }
}
posted @ 2023-03-13 23:35  kiper  阅读(12)  评论(0编辑  收藏  举报