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

LeetCode 303. Range Sum Query - Immutable

2017-05-28 00:10 363 查看

303. Range Sum Query - Immutable

一、问题描述

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

Note:

You may assume that the array does not change.

There are many calls to sumRange function.

二、输入输出

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3


三、解题思路

是按照DP TAG来选的题目,结果这道题我实在是看不出来DP的影子。DP是用来解决最优化问题的,这个题完全就没有最优化的影子。如果每次都从i加到j TLE错误。提示里说了会调用方法很多次。

全新的一个思路,只需要o(n)时间复杂度,o(n)的空间复杂度,如果不用sums数组,而是在原来的nums上修改,空间复杂度就成了o(1)

核心思想就是
sum(i, j) = sum(0, j) - sum(0, i-1)
就是把从0到i的和记录下来,之后让求从i到j的和,主要做一次减法就行了,只需要常数时间。

class NumArray {
public:
vector<int> sums;

NumArray(vector<int> nums) {
if (nums.empty()) return;
sums.push_back(nums[0]);
for (int i = 1; i < nums.size(); ++i) {
int lastSum = sums[i-1];
sums.push_back(lastSum + nums[i]);
}
}

int sumRange(int i, int j) {
if(i == 0) return sums[j];
return (sums[j] - sums[i-1]);
}
};

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