LeetCode 303. Range Sum Query

来源:互联网 发布:grub2启动ubuntu 编辑:程序博客网 时间:2024/05/16 10:54

题目:
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.

思路:
就是求区间i和j之前的值的和,因为是同一个数组,测试用例为取不同的i和j,如果不考虑效率,每次都是i到j的值相加,但是这样如果对同一个数组测试用例多了之后效率很低;所以要考虑效率问题,求出nums的前i个数的值放到sums中,每次只要调用sums[j]-sums[i-1] 即可

代码实现:

class NumArray {public:    NumArray(vector<int> nums) {        if (nums.empty()){//如果nums为空,直接返回            return ;        }        else{            sums.push_back(nums[0]);            //求得给定数列长度            int len = nums.size();            for (int i = 1; i < len; ++i){//分别求nums的前i个和放入sums中                sums.push_back(sums[i - 1] + nums[i]);            }        }    }    int sumRange(int i, int j) {        if (0 == i){            return sums[j];        }        int len = sums.size();        if (i < 0 || i >= len || j < 0 || j >= len || i > j){//如果是这些条件,都是不满足的            return 0;        }        return sums[j] - sums[i-1];//即是sums的前j个和-前i-1个和    }private:    //sums的第i个值即为nums的前i个数的和(i从0开始)    vector<int> sums;};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */

输出结果: 179ms

0 0
原创粉丝点击