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

LeetCode 303. Range Sum Query - Immutable

2017-05-01 11:26 525 查看
题目:

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) -> 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.

思路:

就是求区间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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: