当前位置:网站首页>238. product of arrays other than itself

238. product of arrays other than itself

2022-06-11 21:54:00 Code loving students

Title Description :

Give you an array of integers nums, return Array answer , among answer[i] be equal to nums Middle Division nums[i] Product of other elements .

Topic analysis :

We use the prefix and suffix method to solve this problem

For this problem, we can understand that we need to subscript i The previous subscript is 0~i-1 The element and subscript of are i+1~n Product of elements of .

For this problem, we can set an array to store the product of the elements before this element ( Prefix ).

Then multiply from the last element ( The tails are ).

The code implementation is as follows :

int* productExceptSelf(int* nums, int numsSize, int* returnSize){
    int* a = (int*)malloc(numsSize*sizeof(int));// Set a new array 
    int add = 1;
    for (int i = 0; i < numsSize; i++)
    {
        a[i] = add;      // There is no element before the first element, so it stores 1( The product is itself )
        add *= nums[i];
    }
    add = 1;
    for (int i = numsSize - 1; i >= 0; i--)
    {
        a[i] *= add;         // Product from back to front , The last element is stored as the product of all the previous elements , So by 1
        add *= nums[i];
    }
    *returnSize = numsSize;
    return a;
}

原网站

版权声明
本文为[Code loving students]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112135378717.html