303. Range Sum Query

来源:互联网 发布:好搜刷排名软件 编辑:程序博客网 时间:2024/06/13 18:52

题目

303. Range Sum Query - Immutable

解题思路

给出一串数字,要求出任意区间之间数字的和……解题思路比较简单,再加个长度足够数组存储前i个数字的和避免在后面重复计算造成超时。

具体代码

class NumArray {public:    NumArray(vector<int> nums) {        if (!nums.empty())// 需要考虑到nums长度为0的情况        {            this->sum_of_array.push_back(nums[0]);            for (int i = 1; i < nums.size(); i++) {                this->sum_of_array.push_back(nums[i] + this->sum_of_array[i - 1]);            }        }    }    int sumRange(int i, int j) {        if (i == 0)            return this->sum_of_array[j];        return this->sum_of_array[j] - this->sum_of_array[i-1];    }private:    vector<int> sum_of_array;};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
原创粉丝点击