Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 303. Range Sum Query - Immutable #303

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 303. Range Sum Query - Immutable #303

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

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:

  1. You may assume that the array does not change.
  2. There are many calls to  sumRange  function.

  

这道题让我们检索一个数组的某个区间的所有数字之和,题目中给了两条条件,首先数组内容不会变化,其次有很多的区间和检索。那么我们用传统的遍历相加来求每次区间和检索,十分的不高效,而且无法通过 OJ。所以这道题的难点就在于是否能想到来用建立累计直方图的思想来建立一个累计和的数组 dp,其中 dp[i] 表示 [0, i] 区间的数字之和,那么 [i,j] 就可以表示为 dp[j]-dp[i-1],这里要注意一下当 i=0 时,直接返回 dp[j] 即可,参见代码如下:

 

解法一:

class NumArray {
public:
    NumArray(vector<int> &nums) {
        dp = nums;
        for (int i = 1; i < nums.size(); ++i) {
            dp[i] += dp[i - 1];
        }
    }
    int sumRange(int i, int j) {
        return i == 0? dp[j] : dp[j] - dp[i - 1];
    }
private:
    vector<int> dp;
};

 

当然,我们也可以通过增加一位 dp 的长度,来避免在 sumRange 中检测i是否为0,参见代码如下:

 

解法二:

class NumArray {
public:
    NumArray(vector<int> &nums) {
        dp.resize(nums.size() + 1, 0);
        for (int i = 1; i <= nums.size(); ++i) {
            dp[i] = dp[i - 1] + nums[i - 1];
        }
    }
    int sumRange(int i, int j) {
        return dp[j + 1] - dp[i];
    }
    
private:
    vector<int> dp;
};

 

类似题目:

Range Sum Query 2D - Mutable

Range Sum Query 2D - Immutable

Range Sum Query - Mutable

Maximum Size Subarray Sum Equals k 

 

参考资料:

https://leetcode.com/problems/range-sum-query-immutable/

https://leetcode.com/problems/range-sum-query-immutable/discuss/75184/5-lines-C%2B%2B-4-lines-Python

https://leetcode.com/problems/range-sum-query-immutable/discuss/75192/Java-simple-O(n)-init-and-O(1)-query-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant