Created
May 4, 2016 15:43
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NumArray { | |
public: | |
NumArray(vector<int> &_nums) { | |
if(_nums.empty()) | |
return; | |
nums=_nums; | |
numSum.resize(nums.size(), 0); | |
numSum[0]=nums[0]; | |
for(int i=1; i<nums.size(); i++) | |
numSum[i] = nums[i]+numSum[i-1]; | |
} | |
void update(int i, int val) { | |
int diff = val - nums[i]; | |
nums[i]=val; | |
for(; i<nums.size(); i++) | |
numSum[i]=numSum[i]+diff; | |
} | |
int sumRange(int i, int j) { | |
if(j<i) | |
return 0; | |
if(i==0) | |
return numSum[j]; | |
else{ | |
return numSum[j]-numSum[i-1]; | |
} | |
} | |
vector<int> numSum; | |
vector<int> nums; | |
}; | |
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment