解题思路:
刚上手这道题,第一想法是调用vector的accumulate函数, 直接返回求和,终究是我太年轻了,超时了,代码如下:
class NumArray {
private:
vector<int> nums;
public:
NumArray(vector<int>& nums) {
this->nums = nums;
}
void update(int index, int val) {
nums[index] = val;
}
int sumRange(int left, int right) {
return accumulate(nums.begin() + left, nums.begin() + right + 1, 0);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* obj->update(index,val);
* int param_2 = obj->sumRange(left,right);
*/
紧接着想到前缀和的方法,但是一想到更新数组中元素,又要花费O(N)的时间去修改前缀和数组,无奈超时,代码如下:
class NumArray {
private:
vector<int> nums;
vector<int> pre;
int n;
public:
NumArray(vector<int>& nums) {
this->nums = nums;
n = nums.size();
pre = vector<int>(n + 1, 0);
for(int i = 0; i < n; i ++) {
pre[i + 1] = pre[i] + nums[i];
}
}
void update(int index, int val) {
int change = nums[index] - val;
nums[index] = val;
for(int i = index + 1; i <= n; i ++) {
pre[i] = pre[i] - change;
}
}
int sumRange(int left, int right) {
return pre[right + 1] - pre[left];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* obj->update(index,val);
* int param_2 = obj->sumRange(left,right);
*/
这里涉及一个新的知识点,线段树,通过把每个元素的val存储在线段树中,每个线段树的节点的值为两个子树的和,这样在查找和更新的时候将时间复杂度下降到O(logN),有效解决了超时问题,代码如下:
class NumArray {
private:
vector<int> segmentTree;
int n;
void build(int node, int s, int e, vector<int> &nums) {
// 如果区间仅为node
if (s == e) {
segmentTree[node] = nums[s];
return;
}
int m = s + (e - s) / 2;
// 左子节点递归
build(node * 2 + 1, s, m, nums);
// 右子节点递归
build(node * 2 + 2, m + 1, e, nums);
segmentTree[node] = segmentTree[node * 2 + 1] + segmentTree[node * 2 + 2];
}
// 元素修改,更新线段树
void change(int index, int val, int node, int s, int e) {
if (s == e) {
segmentTree[node] = val;
return;
}
int m = s + (e - s) / 2;
if (index <= m) {// 从左节点找
change(index, val, node * 2 + 1, s, m);
} else { // 从右节点找
change(index, val, node * 2 + 2, m + 1, e);
}
// 线段树统计左右节点求和
segmentTree[node] = segmentTree[node * 2 + 1] + segmentTree[node * 2 + 2];
}
int range(int left, int right, int node, int s, int e) {
// 如果区间范围正好满足
if (left == s && right == e) {
return segmentTree[node];
}
int m = s + (e - s) / 2;
// 区间在左子节点上
if (right <= m) {
return range(left, right, node * 2 + 1, s, m);
} else if (left > m) {// 区间在右子节点上
return range(left, right, node * 2 + 2, m + 1, e);
} else {// 区间在左右节点之间,分成两个区间进行查找
return range(left, m, node * 2 + 1, s, m) + range(m + 1, right, node * 2 + 2, m + 1, e);
}
}
public:
NumArray(vector<int>& nums) : n(nums.size()), segmentTree(nums.size() * 4) {
build(0, 0, n - 1, nums);
}
void update(int index, int val) {
change(index, val, 0, 0, n - 1);
}
int sumRange(int left, int right) {
return range(left, right, 0, 0, n - 1);
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)