LeetCode 238
Product of Array Except Self
Given an array of n integers where n > 1, nums,
return an array output such that output[i] is equal to the product
of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity?
(Note: The output array does not count as extra space
for the purpose of space complexity analysis.)
1 /************************************************************************* 2 > File Name: LeetCode238.c 3 > Author: Juntaran 4 > Mail: Jacinthmail@gmail.com 5 > Created Time: 2016年04月28日 星期四 23时40分01秒 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 Product of Array Except Self 11 12 Given an array of n integers where n > 1, nums, 13 return an array output such that output[i] is equal to the product 14 of all the elements of nums except nums[i]. 15 16 Solve it without division and in O(n). 17 18 For example, given [1,2,3,4], return [24,12,8,6]. 19 20 Follow up: 21 Could you solve it with constant space complexity? 22 (Note: The output array does not count as extra space 23 for the purpose of space complexity analysis.) 24 25 ************************************************************************/ 26 27 #include<stdio.h> 28 29 /** 30 * Return an array of size *returnSize. 31 * Note: The returned array must be malloced, assume caller calls free(). 32 */ 33 int* productExceptSelf(int* nums, int numsSize, int* returnSize) 34 { 35 if( numsSize == 0 ) 36 { 37 return 0; 38 } 39 40 int *result = malloc(numsSize*sizeof(int)); 41 *returnSize = numsSize; 42 43 /* 从左往右 */ 44 int i; 45 int leftProduct = 1; 46 int rightProduct = 1; 47 48 for( i=0; i<numsSize; i++ ){ 49 result[i] = leftProduct; 50 leftProduct *= nums[i]; 51 } 52 /* 从右往左 */ 53 for( i = numsSize - 1; i>=0; i-- ){ 54 result[i] *= rightProduct; 55 rightProduct *= nums[i]; 56 } 57 58 return result; 59 } 60 61 int main(){ 62 63 int nums[] = {1,2,3,4,5,6,7}; 64 int numsSize = 7; 65 int returnSize[numsSize]; 66 productExceptSelf( nums, numsSize, returnSize); 67 return 0; 68 }