My accepted c++ code, It is simple and clear.


  • -1
    F

    My c++ code:

    class NumArray {
    public:
    vector<int> sum;
    vector<int> a;
    
    NumArray(vector<int> &nums) {
        a.clear();
        for(int i=0;i<nums.size();i++){
            a.push_back(nums[i]);
        }
        int temp = 0;
        for(int i=0;i<a.size();i++){
            temp += a[i];
            sum.push_back(temp);
        }
    }
    
    int sumRange(int i, int j) {
        if(i==0){
            return sum[j];
        }else{
            return (sum[j]-sum[i-1]);
        }
    }
    };
    

    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);


  • 0

    vector a seems completely redundant.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.