差分入门模板题目LC.1109航班预订统计(@宫水三叶)

alt alt alt alt alt alt

class Solution {
    public int[] corpFlightBookings(int[][] bookings, int n) {
        int[] c = new int[n + 1];
        for (int[] bs : bookings) {
            int l = bs[0] - 1, r = bs[1] - 1, v = bs[2];
            //在求和过程中,会保证[l,r]区间内都加上v;
            c[l] += v;
            c[r + 1] -= v;
        }
        int[] ans = new int[n];
        ans[0] = c[0];
        for (int i = 1; i < n; i++) {
            ans[i] = ans[i-1] + c[i];
        }
        return ans;
    }
}
//贴一段6个月前的代码,憨厚本厚了属实是。
class Solution {
    public int[] corpFlightBookings(int[][] bookings, int n) {
        int[] ans = new int[n];
        for (int i = 0; i < bookings.length;i++) {
            int first = bookings[i][0];
            int last = bookings[i][1];
            int seats = bookings[i][2];
            for(int j = first;j <= last;j++){
                ans[j - 1] += seats;
            }
        }
        return ans;
    }
}

差分题单(@王悟空)

alt