303. Range Sum Query

来源:互联网 发布:淘宝2元包邮怎么挣钱 编辑:程序博客网 时间:2024/05/18 01:52

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:
You may assume that the array does not change. There are many calls to
sumRange function.

class NumArray {public:    vector<int> startRange;    vector<int> endRange;    int sum = 0;    int size = 0;    NumArray(vector<int> nums) {        if(nums.size()>0){            size = nums.size();            for(int i = 0;i < nums.size();++i){                sum += nums[i];                startRange.push_back(sum);            }            for(int i = 0;i < nums.size();++i){                endRange.push_back(sum);                sum -= nums[i];            }            sum = endRange[0];        }else{            sum = 0;            size = 0;            startRange.push_back(0);            endRange.push_back(0);        }    }    int sumRange(int i, int j) {        int result = endRange[0];        if(i < 0 || j < 0 || i >= size || j >= size || i > j){            return 0;        }        if(i>0){           result -= startRange[i-1];         }               if(j<size-1){           result -= endRange[j+1];         }        return result;    }};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
原创粉丝点击