303. Range Sum Query - Immutable

303. Range Sum Query - Immutable

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

Note:
1.You may assume that the array does not change.
2.There are many calls to sumRange function.

Analysis:
注意note中最后一句manycalls, 所以如果在sumRange 函数中执行for循环那就太费时间了。
还有在做这道题的时候对于for循环注意到了一个问题:for循环先执行判断再执行循环体最后累加

还有就是vector::size 是unsign int型,所以可以试一下:

unsigned int k=0;
cout<<k-1;

有时候这一点不注意会出错。
Source Code(C++):

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class NumArray {
public:
    vector<int> nums_sum;
    NumArray(vector<int> &nums) {
        int temp_sum=0;
        for(int i=0; i<nums.size(); i++) {
            temp_sum +=nums.at(i);
            nums_sum.push_back(temp_sum);
        }
    }
    int sumRange(int i, int j) {
        if (i<0 || j>=nums_sum.size() || i>j){
            return 0;
        }
        if (i==0){
            return nums_sum.at(j);
        }
        else {
            return nums_sum.at(j)-nums_sum.at(i-1);
        }
    }
};

int main() {
    vector<int> nums;
    nums.push_back(-2);
    nums.push_back(0);
    nums.push_back(3);
    nums.push_back(-5);
    nums.push_back(2);
    nums.push_back(-1);
    NumArray numArray(nums);
    cout << numArray.sumRange(0, 2);
    cout << numArray.sumRange(0, 5);
    return 0;
}

你可能感兴趣的:(303. Range Sum Query - Immutable)