Range Sum Query - Immutable Solutions in C++
Number 303
Difficulty Easy
Acceptance 44.9%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/range-sum-query-immutable/// Author : Calinescu Valentin, Hao Chen// Date : 2015-11-10class NumArray {/** Solution* =========** The sum of all the elements starting from position 0 to position i is stored in* sums[i]. This way we can reconstruct the sum from position i to position j by* subtracting sums[i - 1] from sums[j], leaving us with the sum of the desired elements.** Note: we can add a dummy sum at then beginning to simplify the code**/private:int size;vector <long long> sums;public:NumArray(vector<int> &nums): size(nums.size()), sums(size+1, 0) {for(int i=0; i<size; i++) {sums[i+1] = sums[i] + nums[i];}}int sumRange(int i, int j) {return sums[j+1] - sums[i];}};// Your NumArray object will be instantiated and called as such:// NumArray numArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/range-sum-query-immutable/description//// Author : liuyubobobo/// Time : 2017-10-28#include <iostream>#include <vector>using namespace std;class NumArray {private:vector<int> sum;public:NumArray(vector<int> nums) {sum.push_back(0);for(int num: nums)sum.push_back(sum.back() + num);}int sumRange(int i, int j) {i ++;j ++;return sum[j] - sum[i-1];}};int main() {int nums[] = {-2, 0, 3, -5, 2, -1};vector<int> vec(nums, nums + sizeof(nums)/sizeof(int));NumArray obj(vec);cout << obj.sumRange(0, 2) << endl;cout << obj.sumRange(2, 5) << endl;cout << obj.sumRange(0, 5) << endl;return 0;}