前置知识:前缀累加和
作者:互联网
前置知识:前缀累加和
arr[ i ....j ]
求sum[ i, j ]的和 等价于 sum[ i, j ] = preSum[ 0, j ] - preSum[ 0, i-1 ]
前缀和的生成:
index 0 1 2 3 4 5 6
arr [-3, 1, 2, 4, 0, -1, 5] 遍历arr数组一遍preSum数组就能生成好
preSum[-3, -2, 0, 4, 4, 3, 8]
1 package class05; 2 3 public class PreSum { 4 5 public static long[] PreSum(int[] nums) { 6 if (nums == null || nums.length == 0) { 7 return null; 8 } 9 long[] sum = new long[nums.length]; 10 sum[0] = nums[0]; 11 for (int i = 1; i < nums.length; i++) { 12 sum[i] = sum[i - 1] + nums[i]; 13 } 14 return sum; 15 } 16 17 public static void main(String[] args) { 18 int[] arr = {-3, 1, 2, 4, 0,-1,5}; 19 long[] temp = PreSum(arr); 20 for(int i=0; i<temp.length; i++) { 21 System.out.println(temp[i]); 22 } 23 } 24 25 }
标签:arr,前缀,nums,int,sum,前置,long,累加,preSum 来源: https://www.cnblogs.com/yzmarcus/p/16294426.html