forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
238.c
49 lines (38 loc) · 1.14 KB
/
238.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
if (nums == NULL || numsSize == 0) return NULL;
int *output = (int *)malloc(numsSize * sizeof(int));
*returnSize = numsSize;
int i;
for (i = 0; i < numsSize; i++) { /* initialize all outputs to 1 */
output[i] = 1;
}
int prodLeft = 1; /* product from left */
for (i = 1; i < numsSize; i++) {
prodLeft *= nums[i - 1];
output[i] *= prodLeft;
}
int prodRight = 1; /* product from right */
for (i = numsSize - 2; i >= 0; i--){
prodRight *= nums[i + 1];
output[i] *= prodRight;
}
return output;
}
int main() {
int nums[] = { 1, 2, 3, 4 };
int returnSize = 0;
int* output = productExceptSelf(nums, sizeof(nums)/sizeof(nums[0]), &returnSize);
int i;
for (i = 0; i < returnSize; i++) {
printf("%d ", output[i]);
}
printf("\n");
free(output);
return 0;
}