|
| 1 | +# 303. Range Sum Query - Immutable |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: Array, Design, Prefix Sum. |
| 5 | +- Similar Questions: Range Sum Query 2D - Immutable, Range Sum Query - Mutable, Maximum Size Subarray Sum Equals k. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given an integer array `nums`, handle multiple queries of the following type: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +- Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. |
| 14 | + |
| 15 | + |
| 16 | +Implement the `NumArray` class: |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +- `NumArray(int[] nums)` Initializes the object with the integer array `nums`. |
| 21 | + |
| 22 | +- `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +Example 1: |
| 27 | + |
| 28 | +``` |
| 29 | +Input |
| 30 | +["NumArray", "sumRange", "sumRange", "sumRange"] |
| 31 | +[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] |
| 32 | +Output |
| 33 | +[null, 1, -1, -3] |
| 34 | +
|
| 35 | +Explanation |
| 36 | +NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); |
| 37 | +numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 |
| 38 | +numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 |
| 39 | +numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 |
| 40 | +``` |
| 41 | + |
| 42 | + |
| 43 | +**Constraints:** |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +- `1 <= nums.length <= 104` |
| 48 | + |
| 49 | +- `-105 <= nums[i] <= 105` |
| 50 | + |
| 51 | +- `0 <= left <= right < nums.length` |
| 52 | + |
| 53 | +- At most `104` calls will be made to `sumRange`. |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +## Solution |
| 58 | + |
| 59 | +```javascript |
| 60 | +/** |
| 61 | + * @param {number[]} nums |
| 62 | + */ |
| 63 | +var NumArray = function(nums) { |
| 64 | + this.leftSum = Array(nums.length); |
| 65 | + for (var i = 0; i < nums.length; i++) { |
| 66 | + this.leftSum[i] = (this.leftSum[i - 1] || 0) + nums[i]; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * @param {number} left |
| 72 | + * @param {number} right |
| 73 | + * @return {number} |
| 74 | + */ |
| 75 | +NumArray.prototype.sumRange = function(left, right) { |
| 76 | + return this.leftSum[right] - (this.leftSum[left - 1] || 0); |
| 77 | +}; |
| 78 | + |
| 79 | +/** |
| 80 | + * Your NumArray object will be instantiated and called as such: |
| 81 | + * var obj = new NumArray(nums) |
| 82 | + * var param_1 = obj.sumRange(left,right) |
| 83 | + */ |
| 84 | +``` |
| 85 | + |
| 86 | +**Explain:** |
| 87 | + |
| 88 | +nope. |
| 89 | + |
| 90 | +**Complexity:** |
| 91 | + |
| 92 | +* Time complexity : O(1). |
| 93 | +* Space complexity : O(n). |
0 commit comments