array prefix and

1. Prefix and

The concept of prefix sum: prefix sum refers to the sum of elements in all positions in the array from the start position to the current position. It can be calculated by accumulating array elements. Generally speaking, we can use the prefix sum array in constant time complexity Computes the sum over any interval.

Note: Especially in the case of frequent calculation of interval sums, the time complexity can be reduced from O(n) to O(1) by precomputing the prefix and array first.

1. One-dimensional array prefix and

class NumArray {
    private int[] preSum;
    //构造前缀和数组
    public NumArray(int[] nums) {
      int n=nums.length;
      preSum=new int[n+1];
     for(int i=1;i<preSum.length;i++){
         preSum[i]=preSum[i-1]+nums[i-1];
     }
    }
    //查询(left,right)中的元素之和
    public int sumRange(int left, int right) {
     return preSum[right+1]-preSum[left];
    }
}

2. Two-dimensional array prefix and

class NumMatrix {
    //构造二维数组
    private int[][] preSum;
    public NumMatrix(int[][] matrix) {
     int row=matrix.length;
     int colum=matrix[0].length;
     preSum=new int[row+1][colum+1];
     for(int i=1;i<preSum.length;i++){
         for(int j=1;j<preSum[0].length;j++){
             preSum[i][j]=preSum[i-1][j]+preSum[i][j-1]+matrix[i-1][j-1]-preSum[i-1][j-1];
         }
     }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
       return preSum[row2+1][col2+1]-preSum[row1][col2+1]-preSum[row2+1][col1]+preSum[row1][col1];
    }
}

 

 

Suppose if there is a two-dimensional array now, how do you calculate the prefix sum of the two-dimensional array?

 

We first create a two-dimensional array of length n+1

 

Here we need to know how to calculate the area of ​​a two-dimensional array

 

 

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/131555725