Thursday, September 14, 2017

303. Range Sum Query - Immutable

https://leetcode.com/problems/range-sum-query-immutable/description/
Solution 1. Because:
You may assume that the array does not change.
There are many calls to sumRange function.
It is better to calculate sum when initialize the object.
class NumArray {
    vector<int> sm;
public:
    NumArray(vector<int> nums) {
        sm.resize(nums.size()+1, 0);
        for(int i=0; i<nums.size(); i++)
            sm[i+1] = sm[i] + nums[i];
    }
 
    int sumRange(int i, int j) {
        return sm[j+1] - sm[i];
    }
};
Solution 2. do not calculate sum at initialization. Much slower.
class NumArray {
    vector<int> n;
public:
    NumArray(vector<int> nums) {
        n = nums;
    }
 
    int sumRange(int i, int j) {
        int s = 0;
        for(int k=i; k<=j; k++)
            s += n[k];
        return s;
    }

};

No comments:

Post a Comment