LeetCode Range Sum Query - Immutable

来源:互联网 发布:站内搜索引擎优化 编辑:程序博客网 时间:2024/06/05 05:12

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change
  2. There are many calls to sumRange function.
这个题的主要思路是为了防止频繁的sumRange操作导致大量的重复计算,因此在系统里面存上从0-j的元素的总和,这样在sumRange的时候可以直接按照位置关系相减即可,不用重复计算

class NumArray {public:    //这个题的主要思路是为了防止频繁的sumRange操作导致大量的重复计算,因此在系统里面存上从0-j的元素的总和,这样在sumRange的时候可以直接按照位置关系相减即可,不用重复计算    vector<int> array;    NumArray(vector<int> &nums) {        for(int i=0;i<nums.size();i++)           array.push_back(nums[i]);        for(int i= 1;i<nums.size();i++)           array[i] += array[i-1];    }    int sumRange(int i, int j) {        if(i<0||j>=array.size()||i>j) return 0;        int total = 0;        if(i==0)            total = array[j];        else            total = array[j] - array[i-1];        return total;    }};// Your NumArray object will be instantiated and called as such:// NumArray numArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);


0 0
原创粉丝点击