Skip to content

Commit 03d4b88

Browse files
authored
Create 16_rangeSumQuery.cpp
1 parent 9d551b4 commit 03d4b88

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class NumArray { // 12 ms, faster than 99.87%
2+
public:
3+
vector<int>& preSum; // `preSum` will reference to `nums` array, no copy at all!
4+
5+
NumArray(vector<int>& nums) : preSum(nums) {
6+
for (int i = 1; i < preSum.size(); ++i)
7+
preSum[i] += preSum[i-1];
8+
}
9+
10+
int sumRange(int left, int right) {
11+
if (left == 0) return preSum[right];
12+
return preSum[right] - preSum[left-1];
13+
}
14+
};

0 commit comments

Comments
 (0)