java.lang.Object
g0301_0400.s0303_range_sum_query_immutable.NumArray

public class NumArray extends Object
303 - Range Sum Query - Immutable.<p>Easy</p> <p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left <= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p><strong>Example 1:</strong></p> <p><strong>Input</strong></p> <pre><code> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] </code></pre> <p><strong>Output:</strong> [null, 1, -1, -3]</p> <p><strong>Explanation:</strong></p> <pre><code> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums.length <= 10<sup>4</sup></code></li> <li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li> <li><code>0 <= left <= right < nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
  • Constructor Details

    • NumArray

      public NumArray(int[] nums)
  • Method Details

    • sumRange

      public int sumRange(int i, int j)