19.leetcode题目303: Range Sum Query - Immutable

来源:互联网 发布:java poi 跨行合并 编辑:程序博客网 时间:2024/05/22 18:56

题目:

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.
分析:其实我没有看懂这道题的note,也没看懂给定的框架下面注释掉的语句是干嘛的。

</pre><pre name="code" class="cpp">class NumArray {vector<int> sums;public:    NumArray(vector<int> &nums) {        sums=nums;      //这一步缺少了就会运行错误,这是为什么?        if(nums.size()!=0){            //sums[0]=nums[0];        for(int i=1;i<nums.size();i++){            sums[i]+=sums[i-1];    //sums[i]=nums[i]+sums[i-1];这句话运行比<span style="font-family: Arial, Helvetica, sans-serif;">sums[i]+=sums[i-1];这句话快了4ms</span>        }        }    }    int sumRange(int i, int j) {        if(i>=0)        return i==0?sums[j]:(sums[j]-sums[i-1]);        else         return 0;    }};// Your NumArray object will be instantiated and called as such:// NumArray numArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);


利用sums存储子序列的和,sums[i]表示nums从0到i的所有元素的和,则i、j之间的所有元素的和为:sums[j]-sums[i-1],如果i==0,则直接返回sums[j]。

运行时间592ms




0 0