[leetcode]: 303. Range Sum Query

来源:互联网 发布:手机数据共享怎么用 编辑:程序博客网 时间:2024/06/05 21:52

1.题目

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
给一个整型数组,返回下标i~j之间的元素和。
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.

2.分析

数组不会变,所以可以事先计算好sum存在数组中,查询时根据下标返回即可。

3.代码

class NumArray {public:    NumArray(vector<int> nums) {        sum = nums;        for (int i = 1; i < nums.size(); i++)            sum[i] += sum[i - 1];    }    int sumRange(int i, int j) {        return i == 0 ? sum[j] : sum[j] - sum[i - 1];    }private:    vector<int> sum;};
原创粉丝点击