1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-11 02:58:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode-cn/problem (English)/区域和检索 - 数组不可变(English) [range-sum-query-immutable].html

40 lines
1.6 KiB
HTML
Raw Normal View History

2022-03-27 20:56:26 +08:00
<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 &lt;= 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>&nbsp;</p>
2023-12-09 18:42:21 +08:00
<p><strong class="example">Example 1:</strong></p>
2022-03-27 20:56:26 +08:00
<pre>
<strong>Input</strong>
[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
<strong>Output</strong>
[null, 1, -1, -3]
<strong>Explanation</strong>
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
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li>
</ul>