class Difference
{
public:
int* diff;
int* res;
int _size;
Difference(int nums[],int size);
void decrease(int(&arr)[3]);
int* result();
~Difference();
};
Difference::Difference(int nums[], int size):_size(size)
{
if (_size< 0)return;
diff= new int[_size];
diff[0] = nums[0];
for (auto i = 1; i < _size; ++i)
{
diff[i] = nums[i] - nums[i - 1];
}
}
void Difference::decrease(int(&arr)[3])
{
diff[arr[0]] += arr[2];
if (arr[1] + 1 < _size)
{
diff[arr[1] + 1] -= arr[2];
}
}
int* Difference::result()
{
res = new int[_size];
res[0] = diff[0];
for (int i = 1; i < _size; ++i)
{
res[i] = res[i - 1] + diff[i];
}
return res;
}
Difference::~Difference()
{
delete diff;
delete res;
}
int main()
{
int arr[5] = { 0,0,0,0,0 };
int length = sizeof(arr) / sizeof(int);
int action[3] = { 1,3,2 };
Difference DE(arr, length);
DE.decrease(action);
DE.result();
for (int i = 0; i < 5; ++i)
{
cout << DE.res[i] << endl;
}
system("pause");
return 0;
}
力扣第 370 题「 区间加法」 就直接考察了差分数组技巧
最新推荐文章于 2023-01-28 23:29:20 发布
这个博客展示了如何使用C++定义一个名为Difference的类,该类用于存储数组的差分,并提供了更新差分值的方法。通过decrease()函数,可以针对指定索引的差分值进行增加或减少操作,然后result()方法返回计算后的累积结果数组。
摘要由CSDN通过智能技术生成