File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Given an integer array nums, handle multiple queries of the following type:
3+
4+ Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
5+
6+ Implement the NumArray class:
7+
8+ - NumArray(int[] nums) Initializes the object with the integer array nums.
9+ - int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right
10+ inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
11+
12+ */
13+
14+
15+ class NumArray {
16+ public:
17+ vector<int > prefixSum;
18+ NumArray (vector<int >& nums) {
19+ int count=0 ;
20+ for (int i=0 ;i<nums.size ();i++){
21+ count+=nums[i];
22+ prefixSum.push_back (count);
23+ }
24+ }
25+
26+ int sumRange (int left, int right) {
27+ int answer=prefixSum[right];
28+
29+ if (left-1 >=0 ){
30+ answer-=prefixSum[left-1 ];
31+ }
32+ return answer;
33+ }
34+ };
35+
36+ /* *
37+ * Your NumArray object will be instantiated and called as such:
38+ * NumArray* obj = new NumArray(nums);
39+ * int param_1 = obj->sumRange(left,right);
40+ */
You can’t perform that action at this time.
0 commit comments