您的位置:首页 > 产品设计 > UI/UE

LeetCode -- Range Sum Query - Immutable

2017-08-01 10:54 162 查看

题目:

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

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.

思路:

这道题是简单的动态规划的思想,参考了别人的思路后写出了
O(n)
的构建时间复杂度,
O(1)
的查询时间复杂度。构建一个
vector
记录
nums
的和,如下:

i0123456
nums-203-52-1
sum0-2-21-4-2-3
此时,
sumRange(i, j) = sum[j+1]-sum[i]
j+1
是因为为了使代码简洁,刚开始的时候向
sum
push了一个0。

C++代码实现:

class NumArray {
public:
NumArray(vector<int> nums) {
sum.push_back(0);
for(int i=0; i<nums.size(); ++i){
sum.push_back(sum.back() + nums[i]);
}
}

int sumRange(int i, int j) {
return sum[j+1]-sum[i];
}
private:
vector<int> sum;
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c-c++