304. Range Sum Query 2D - Immutable Medium
1/**
2 * [304] Range Sum Query 2D - Immutable
3 *
4 * Given a 2D matrix matrix, handle multiple queries of the following type:
5 *
6 * Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
7 *
8 * Implement the NumMatrix class:
9 *
10 * NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
11 * int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
12 *
13 * You must design an algorithm where sumRegion works on O(1) time complexity.
14 *
15 * Example 1:
16 * <img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" style="width: 415px; height: 415px;" />
17 * Input
18 * ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
19 * [[[[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]]
20 * Output
21 * [null, 8, 11, 12]
22 * Explanation
23 * 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]]);
24 * numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
25 * numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
26 * numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
27 *
28 *
29 * Constraints:
30 *
31 * m == matrix.length
32 * n == matrix[i].length
33 * 1 <= m, n <= 200
34 * -10^4 <= matrix[i][j] <= 10^4
35 * 0 <= row1 <= row2 < m
36 * 0 <= col1 <= col2 < n
37 * At most 10^4 calls will be made to sumRegion.
38 *
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/range-sum-query-2d-immutable/
43// discuss: https://leetcode.com/problems/range-sum-query-2d-immutable/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47struct NumMatrix {
48 vec![]
49 }
50
51
52/**
53 * `&self` means the method takes an immutable reference.
54 * If you need a mutable reference, change it to `&mut self` instead.
55 */
56impl NumMatrix {
57
58 fn new(matrix: Vec<Vec<i32>>) -> Self {
59
60 }
61
62 fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 {
63
64 }
65}
66
67/**
68 * Your NumMatrix object will be instantiated and called as such:
69 * let obj = NumMatrix::new(matrix);
70 * let ret_1: i32 = obj.sum_region(row1, col1, row2, col2);
71 */
72
73// submission codes end
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn test_304() {
81 }
82}
83
Back
© 2025 bowen.ge All Rights Reserved.