303. Range Sum Query - Immutable

来源:互联网 发布:比较好的网红的淘宝店 编辑:程序博客网 时间:2024/05/17 08:41

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:
Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

思路:很简单,就是用一个数组nums存到每个位置时候的和,求i,j之间的时候就用nums[j]-nums[i-1]就可以了。开始写的时候没有对nums初始化,所以一直报错。

class NumArray {public:     vector<int> sums;public:    NumArray(vector<int> &nums) {        sums = vector<int>(nums.size()+1,0);  // 开始没在这儿初始化就报错了        //sums[0] = 0;        for(int i = 0; i < nums.size(); i++)        {            sums[i+1] = nums[i] + sums[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);
0 0
原创粉丝点击