标签:
Fenwick tree can do this job.
class NumArray { vector<int> in; vector<int> ft; int query(int i) { i += 1; i = min(i, int(ft.size() - 1)); int s = 0; for (; i > 0; i -= (i & -i)) s += ft[i]; return s; } void init(int i, int v) { i += 1; for (; i < ft.size(); i += (i & -i)) ft[i] += v; } public: NumArray(vector<int> &nums) { in = nums; int n = nums.size(); ft.assign(n + 1, 0); for(int i = 0; i < n; i ++) init(i, nums[i]); } void update(int i, int v) { int d = v - in[i]; in[i] = v; i += 1; for (; i < ft.size(); i += (i & -i)) ft[i] += d; } int sumRange(int i, int j) { return query(j) - (i ? query(i - 1) : 0); } };
LeetCode "Range Sum Query - Mutable"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4976464.html