File tree Expand file tree Collapse file tree 1 file changed +10
-13
lines changed
algorithms/cpp/rangeSumQuery-Immutable Expand file tree Collapse file tree 1 file changed +10
-13
lines changed Original file line number Diff line number Diff line change 2020 ***************************************************************************************/
2121
2222class NumArray {
23- public:
2423/*
2524 * Solution
2625 * =========
2726 *
2827 * The sum of all the elements starting from position 0 to position i is stored in
2928 * sums[i]. This way we can reconstruct the sum from position i to position j by
3029 * subtracting sums[i - 1] from sums[j], leaving us with the sum of the desired elements.
30+ *
31+ * Note: we can add a dummy sum at then beginning to simplify the code
3132 *
3233 */
34+ private:
35+ int size;
3336 vector <long long > sums;
34- NumArray (vector<int > &nums) {
35- if (nums.size ())
36- {
37- sums.push_back (nums[0 ]);
38- for (int i = 1 ; i < nums.size (); i++)
39- sums.push_back (sums[i-1 ] + nums[i]);
40- }
37+ public:
38+ NumArray (vector<int > &nums): size(nums.size()), sums(size+1 , 0 ) {
39+ for (int i=0 ; i<size; i++) {
40+ sums[i+1 ] = sums[i] + nums[i];
41+ }
4142 }
4243 int sumRange (int i, int j) {
43- if (i > 0 )
44- return sums[j] - sums[i - 1 ];
45- else
46- return sums[j];
44+ return sums[j+1 ] - sums[i];
4745 }
48-
4946};
5047
5148
You can’t perform that action at this time.
0 commit comments