解题思路
左右乘积表,分别计算i
左侧和右侧乘积。
代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// Function to compute the product of all elements in the input array except the current element
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
// Arrays to store the product of elements to the left and right of each element
int leftProduct[numsSize];
int rightProduct[numsSize];
// Calculate the product of elements to the left of each element
leftProduct[0] = 1;
for (int i = 1; i < numsSize; i++) {
leftProduct[i] = leftProduct[i - 1] * nums[i - 1];
}
// Calculate the product of elements to the right of each element
rightProduct[numsSize - 1] = 1;
for (int j = numsSize - 2; j >= 0; j--) {
rightProduct[j] = rightProduct[j + 1] * nums[j + 1];
}
// Set the return size for the caller
*returnSize = numsSize;
// Compute the final product array by multiplying left and right products
int* Answer = (int*)malloc(sizeof(int) * numsSize);
for (int k = 0; k < numsSize; k++) {
Answer[k] = leftProduct[k] * rightProduct[k];
}
return Answer;
}