问题
TC:O(n*m) 用于创建前缀[][] 总和矩阵,O(row1 row2) 用于计算给定矩形的总和
SC:使用前缀[][]和矩阵的O(n*m)
class NumMatrix { int prefix[][]; public NumMatrix(int[][] matrix) { prefix = new int[matrix.length][matrix[0].length]; for(int i=0;i<matrix.length;i++){ int current = 0; for(int j = 0;j<matrix[0].length;j++){ current+=matrix[i][j]; prefix[i][j] = current; } } } public int sumRegion(int row1, int col1, int row2, int col2) { int sum =0; for(int i =row1;i<=row2;i++){ int right = prefix[i][col2]; int left = (col1>0) ? prefix[i][col1-1] : 0; sum+=right-left; } return sum; } } /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */
以上是范围总和查询 - 不可变的详细内容。更多信息请关注PHP中文网其他相关文章!