LeetCode Range Sum Query - Immutable & Range Sum Query 2D - Immutable

来源:互联网 发布:java与xml 第三版 pdf 编辑:程序博客网 时间:2024/05/21 17:49

Range Sum Query - Immutable

Description:

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Solution:

dp

<span style="font-size:18px;">import java.util.*;public class NumArray {int sums[];public NumArray(int[] nums) {int n = nums.length;sums = new int[n + 1];sums[0] = 0;for (int i = 1; i <= n; i++)sums[i] = sums[i - 1] + nums[i - 1];}public int sumRange(int i, int j) {return sums[j + 1] - sums[i];}}</span>


Range Sum Query 2D - Immutable

Description:

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Solution:

also dp

Just need to notice one point: the initial part, sums[i][j] = mat[i][j] + sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1];

But the query part is sums[r2][c2] + sums[r1][c1] - sums[r2][c1] - sums[r1][c2];

<span style="font-size:18px;">import java.util.*;public class NumMatrix {int sums[][];public NumMatrix(int[][] matrix) {if (matrix == null)return;int n = matrix.length;if (n == 0)return;int m = matrix[0].length;sums = new int[n + 1][m + 1];for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {sums[i][j] = matrix[i - 1][j - 1] - sums[i - 1][j - 1]+ sums[i - 1][j] + sums[i][j - 1];}}}public int sumRegion(int row1, int col1, int row2, int col2) {row2++;col2++;return sums[row2][col2] + sums[row1][col1] - sums[row1][col2]- sums[row2][col1];}}</span>


0 0