代码实现:
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* productExceptSelf(int *nums, int numsSize, int *returnSize) { // 左乘积 int l[numsSize]; l[0] = 1; for (int i = 1; i < numsSize; i++) { l[i] = l[i - 1] * nums[i - 1]; } // 右乘积 int r[numsSize]; r[numsSize - 1] = 1; for (int i = numsSize - 2; i >= 0; i--) { r[i] = r[i + 1] * nums[i + 1]; } int *answer = malloc(sizeof(int) * numsSize); *returnSize = numsSize; for (int i = 0; i < numsSize; i++) { answer[i] = l[i] * r[i]; // 左 * 右 } return answer; }