307. Range Sum Query - Mutable

该博客主要讨论LeetCode中的307题,涉及如何在给定整数数组nums中,实现对元素范围i到j(包括i和j)的和进行查询。提供了update函数来修改数组元素,并强调了数组更新后的range查询策略,即通过维护一个辅助vector num,使得num[i]表示nums前i项的和,从而能快速计算range并处理边界条件。
摘要由CSDN通过智能技术生成

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值