一维前缀和: public class Main { private static final int N = 100010; public static void main(String[] args) { int[] s = new int[N]; int[] a = new int[N]; int n = 10;// 定义10个数 for (int i = 1; i <= n; i++) { a[i] = (int) (Math.random() * 10); } for (int i = 1; i <= n; i++) { s[i] = s[i - 1] + a[i]; } int l = 1, r = 3;// 定义初始和结束位置 System.out.println(s[r] - s[l - 1]); } }
二维前缀和:
S[i, j] = 第i行j列格子左上部分所有元素的和
以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵的和为:
S[x2, y2] - S[x1 - 1, y2] - S[x2, y1 - 1] + S[x1 - 1, y1 - 1]