定义
对于数组 A[n]
,它的差分数组为:
显然,通过差分数组 diff[n]
,可以求得 A[n]
中的某一具体元素:
应用
- 数组
A[n]
从下标j
开始的元素,都增加v
。(即A[j, j+1, ..., n-1] += v
)
- 数组
A[n]
在区间[L, R]
内的元素,都增加v
。(即A[L, L+1, ..., R] += v
)
- 数组
A[n]
中的某一元素A[j]
增加v
。
例题
int* corpFlightBookings(int** bookings, int bookingsSize, int* bookingsColSize, int n, int* returnSize) {
int *ret = (int*)calloc(n, sizeof(int));
memset(ret, 0, n * sizeof(int));
for (int i = 0; i < bookingsSize; i++)
{
for (int j = bookings[i][0] - 1; j < bookings[i][1]; j++)
{
ret[j] += bookings[i][2];
}
}
*returnSize = n;
return ret;
}
差分数组
int* corpFlightBookings(int** bookings, int bookingsSize, int* bookingsColSize, int n, int* returnSize) {
int *ret = (int*)calloc(n, sizeof(int)), *diff = (int*)calloc(n, sizeof(int));
memset(ret, 0, n * sizeof(int));
memset(diff, 0, n * sizeof(int));
*returnSize = n;
for (int i = 0; i < bookingsSize; i++)
{
diff[bookings[i][0] - 1] += bookings[i][2];
if (bookings[i][1] < n)
diff[bookings[i][1]] -= bookings[i][2];
}
ret[0] = diff[0];
for (int i = 1; i < n; i++)
ret[i] = diff[i] + ret[i - 1];
return ret;
}
完
标签:int,差分,bookings,ret,数组,diff,sizeof From: https://www.cnblogs.com/hoyd/p/18102435