LeetCode307. Range Sum Query - Mutable二叉索引树实战

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), 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.
实现:
class BIT {
public:
	BIT(std::vector<int>& v);
	void update(int i, int val);
	int sum(int n);
private:
	int lowbit(int a);
	void preProcessing(const std::vector<int>& v);
	vector<int> vec;
	vector<int>&nums;
};

BIT::BIT(std::vector<int>& v):nums(v)
{
	vec.resize(v.size() + 1);
	preProcessing(v);
}

void BIT::preProcessing(const std::vector<int>& v)
{
	int n = vec.size();
	for (int i = 0; i < v.size(); i++) {
		int m = i + 1;
		while (m < n) {
			vec[m] += v[i];
			m += lowbit(m);
		}
	}
}

void BIT::update(int i, int val)
{
	int diff = val - nums[i];
	nums[i] = val;
	i = i + 1;
	int n = vec.size();
	while (i < n) {
		vec[i] += diff;
		i += lowbit(i);
	}
}

int BIT::sum(int n)
{
	n = n + 1;
	int sum = 0;
	while (n > 0) {
		sum += vec[n];
		n -= lowbit(n);
	}
	return sum;
}

int BIT::lowbit(int a)
{
	return a & (-a);
}

class NumArray {
public:
public:
	NumArray(vector<int> &nums) :bit(nums) {
	}

	void update(int i, int val) {
		bit.update(i, val);
	}

	int sumRange(int i, int j) {
		return bit.sum(j) - bit.sum(i-1);
	}
private:
	BIT bit;
};


你可能感兴趣的:(LeetCode,面试题,二叉索引树)