307. Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

vector<int> num,num[i]意义是nums的第0项到第i项的和,计算range(i,j)时只需要计算num[j]-num[i-1],要考虑边界情况,并且在更新数组中某个位置处的值后,应该更新对应的num

Code:

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
class NumArray
{
private:
	vector<int> num;
public:
	NumArray(vector<int> nums)
	{
		num.resize(nums.size(), 0);
		if (nums.size() > 0)num[0] = nums[0];
		for (int i = 1; i < nums.size(); i++)num[i] = num[i - 1] + nums[i];
	}
	void update(int i, int val)
	{
		int cha = (i == 0 ? 0 : num[i - 1]) - num[i] + val;
		for (int a = i; a < num.size(); a++)num[a] += cha;
	}
	int sumRange(int i, int j)
	{
		if (i == 0)return num[j];
		return num[j] - num[i - 1];
	}
};
int main()
{
	vector<int> nums{ 9, - 8 };
	NumArray* obj = new NumArray(nums);
	int param_1 = obj->sumRange(1, 1);
	obj->update(0, 3);
	int param_2 = obj->sumRange(0, 1);
	cout << param_1 << " " << param_2 << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34229391/article/details/81079845