Product of Array Except Self

来源:互联网 发布:淘宝怎么做排名靠前 编辑:程序博客网 时间:2024/05/17 06:49

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.)


思路

恩,整体就是分成两部分,以自己为分界,前一部分,后一部分

比如A[7]
B[3]: a[0]a[1]a[2] / a[6]a[5]a[4]
B[4]: a[0]a[1]a[2]a[3] / a[6]a[5]

前一部分,正序,用到之前的结果
后一部分,逆序,用到之前的结果,但有个临时变量存储


注意事项

大概就是初值赋值1,然后for的条件


代码

/** * 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) {    int * ret = (int *)malloc(sizeof(int)*numsSize);    if(ret)    {        ret[0] = ret[numsSize-1] = 1;        int i;        int tmp;        for(i = 1; i<numsSize;i++)        {            ret[i] = ret[i-1]*nums[i-1];        }        tmp = 1;        for(i = numsSize-1;i>=0;i--)        {            ret[i]=ret[i]*tmp;            tmp *= nums[i];        }        * returnSize = numsSize;    }    return ret;}
0 0
原创粉丝点击