|
| 1 | +<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> |
| 2 | + |
| 3 | +<ul> |
| 4 | + <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> |
| 5 | +</ul> |
| 6 | + |
| 7 | +<p>Implement the <code>NumMatrix</code> class:</p> |
| 8 | + |
| 9 | +<ul> |
| 10 | + <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> |
| 11 | + <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> |
| 12 | +</ul> |
| 13 | + |
| 14 | +<p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> |
| 15 | + |
| 16 | +<p> </p> |
| 17 | +<p><strong class="example">Example 1:</strong></p> |
| 18 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" style="width: 415px; height: 415px;" /> |
| 19 | +<pre> |
| 20 | +<strong>Input</strong> |
| 21 | +["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] |
| 22 | +[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] |
| 23 | +<strong>Output</strong> |
| 24 | +[null, 8, 11, 12] |
| 25 | + |
| 26 | +<strong>Explanation</strong> |
| 27 | +NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); |
| 28 | +numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) |
| 29 | +numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) |
| 30 | +numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p> </p> |
| 34 | +<p><strong>Constraints:</strong></p> |
| 35 | + |
| 36 | +<ul> |
| 37 | + <li><code>m == matrix.length</code></li> |
| 38 | + <li><code>n == matrix[i].length</code></li> |
| 39 | + <li><code>1 <= m, n <= 200</code></li> |
| 40 | + <li><code>-10<sup>4</sup> <= matrix[i][j] <= 10<sup>4</sup></code></li> |
| 41 | + <li><code>0 <= row1 <= row2 < m</code></li> |
| 42 | + <li><code>0 <= col1 <= col2 < n</code></li> |
| 43 | + <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> |
| 44 | +</ul> |
0 commit comments