标签 算法 下的文章

function calculatePrefixSum(matrix) {  
    const rows = matrix.length;  
    const cols = matrix[0].length;  
    const prefixSum = new Array(rows + 1);  
  
    // 初始化前缀和数组的第一行和第一列  
    for (let i = 0; i <= rows; i++) {  
        prefixSum[i] = new Array(cols + 1).fill(0);  
    }  
  
    // 计算前缀和  
    for (let i = 1; i <= rows; i++) {  
        for (let j = 1; j <= cols; j++) {  
            prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1];  
        }  
    }  
  
    return prefixSum;  
}  
  
function sumSubmatrix(prefixSum, x1, y1, x2, y2) {  
    return prefixSum[x2][y2] - prefixSum[x1 - 1][y2] - prefixSum[x2][y1 - 1] + prefixSum[x1 - 1][y1 - 1];  
}  
  
// 示例用法  
const matrix = [  
    [1, 2, 3],  
    [4, 5, 6],  
    [7, 8, 9]  
];  
  
const prefixSum = calculatePrefixSum(matrix);  
const x1 = 1, y1 = 1, x2 = 2, y2 = 2;  
const sum = sumSubmatrix(prefixSum, x1, y1, x2, y2);  
  
console.log(`子矩阵(${x1}, ${y1}) 到 (${x2}, ${y2}) 的和: ${sum}`);

function calculatePrefixSum(array) {  
   const prefixSumArray = new Array(array.length + 1).fill(0); // 初始化长度为array.length + 1的前缀和数组,并全部填充为0  
   for (let i = 0; i < array.length; i++) {  
       prefixSumArray[i + 1] = prefixSumArray[i] + array[i]; // 计算前缀和,注意索引+1  
   }  
   return prefixSumArray;  
}  
 
// 示例用法  
const array = [1, 2, 3, 4, 5];  
const prefixSumArray = calculatePrefixSum(array);  
 
console.log("原始数组:", array);  
console.log("前缀和数组:", prefixSumArray);  
 
// 计算从索引i到索引j(包含j)的子数组的和  
function sumSubarray(prefixSumArray, i, j) {  
   return prefixSumArray[j + 1] - prefixSumArray[i]; // 注意索引+1  
}  
 
const i = 1; // 子数组的起始索引(从0开始)  
const j = 3; // 子数组的结束索引(从0开始)  
const subarraySum = sumSubarray(prefixSumArray, i, j);  
console.log(`子数组(${i}, ${j}) 的和: ${subarraySum}`);