leetcodeRange Sum Query - Immutable

//先走一遍C++吧,最近一直写Python,老忘记打分号


class NumArray {
    vector<int> mynums;
public:
    NumArray(vector<int> &nums) {
        vector<int> tmp=nums;
        if(tmp.size()>=1) mynums.push_back(tmp[0]);
        for(int i = 1;i < tmp.size();i++)
        {
            mynums.push_back(mynums[i-1]+tmp[i]);
        }
        
    }

    int sumRange(int i, int j) {
        if(i == 0) return mynums[j];
        else return mynums[j]-mynums[i-1];
        
    }
};


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
这是我写的,速度一般般吧

看到有个大神写的,超级简练

class NumArray {
private:
    vector<int> acc;
    
public:
    NumArray(vector<int> &nums) {
        acc.push_back(0);
        for (auto n : nums) {
            acc.push_back(acc.back() + n);
        }
    }

    int sumRange(int i, int j) {
        return acc[j + 1] - acc[i];
    }
};


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
很简练,不得不服。


你可能感兴趣的:(LeetCode,C++)