一. 題目描述
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:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
二. 題目分析
題目在Range Sum Query - Immutable一題的基礎上增加的難度,要求在輸入數組nums後,能夠修改數組的元素,每次只修改一個元素。同樣要實現求數組的某個區間和的功能。
如果在一題的做法上稍加改進,是可以實現功能的,但是會超時。
這時閱讀了一些文章後才發現原來經典的做法(包括前一題)是使用樹狀數組來維護這個數組nums,其插入和查詢都能做到O(logn)的復雜度,十分巧妙。
三. 示例代碼
// 超時
class NumArray {
public:
NumArray(vector &nums) {
if (nums.empty()) return;
else
{
sums.push_back(nums[0]);
//求得給定數列長度
int len = nums.size();
for (int i = 1; i < len; ++i)
sums.push_back(sums[i - 1] + nums[i]);
}
}
void update(int i, int val) {
for (int k = i; k < nums.size(); ++k)
sums[k] += (val - nums[i]);
nums[i] = val;
}
int sumRange(int i, int j) {
return sums[j] - sums[i - 1];
}
private:
vector nums;
//存儲數列和
vector sums;
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);
// 使用樹狀數組實現的代碼AC,復雜度為O(logn)
class NumArray {
private:
vector c;
vector m_nums;
public:
NumArray(vector &nums) {
c.resize(nums.size() + 1);
m_nums = nums;
for (int i = 0; i < nums.size(); i++){
add(i + 1, nums[i]);
}
}
int lowbit(int pos){
return pos&(-pos);
}
void add(int pos, int value){
while (pos < c.size()){
c[pos] += value;
pos += lowbit(pos);
}
}
int sum(int pos){
int res = 0;
while (pos > 0){
res += c[pos];
pos -= lowbit(pos);
}
return res;
}
void update(int i, int val) {
int ori = m_nums[i];
int delta = val - ori;
m_nums[i] = val;
add(i + 1, delta);
}
int sumRange(int i, int j) {
return sum(j + 1) - sum(i);
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);
四. 小結
之前只是聽過,這是第一次使用樹狀數組,這是維護數組的一個很好的思想,需要深入學習!