Topic: Give you an integer array nums of length n, where n> 1, and return the output array output, where output[i] is equal to the product of the remaining elements in nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Tip: The title data ensures that the product of all prefix elements and suffixes (or even the entire array) of any element in the array is in In the 32-bit integer range.
Explanation: Please do not use division, and complete this question in O(n) time complexity.
Source: LeetCode
Link: https://leetcode-cn.com/problems/product-of-array-except-self The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Code:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* productExceptSelf(int* nums, int numsSize, int* returnSize){
int L[numsSize],R[numsSize];
L[0]=1;
for(int i=1;i<numsSize;i++){
L[i]=nums[i-1]*L[i-1];
}
R[numsSize-1]=1;
for(int i=numsSize-2;i>=0;i--){
R[i]=nums[i+1]*R[i+1];
}
int *results = (int *)malloc(sizeof(int)*numsSize);
for(int i=0;i<numsSize;i++){
results[i]=L[i]*R[i];
}
*returnSize=numsSize;
return results;
}