LC370.区间加法
思路:差分
- 差分数组
- 将原始数组视为差分数组的前缀和
nums[0] = diff[0]
num[i] = nums[i - 1] + diff[i]
- 注意相加的区间
代码
```c class Solution { public: vectorgetModifiedArray(int length, vector >& updates) { int n = updates.size();
vector<int> diff(length + 1, 0);
for (int i = 0; i < n; ++i) {
int begin_pos = updates[i][0];
int end_pos = updates[i][1];
int num = updates[i][2];
diff[begin_pos] += num;
diff[end_pos + 1] -= num;
}
vector<int> nums(length, 0);
for (int i = 0; i < length; i++) {
if (i == 0) {
nums[0] = diff[0];
} else {
nums[i] = nums[i - 1] + diff[i];
}
}
return nums;
}
}; ```