Leetcode 238:Product of Array Except Self

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].
【题目大意】给定一个数组a,需要返回一个数组b,数组b的第i个,也就是b[i]表示的是数组a中除了a[i]之外所有其他数字的乘积。
【要求】
1:不允许使用除法
2:O(n)的算法
【解法】
因为要求不能使用除法,所以最简便的一种方法就不可以了,就是先求出所有元素的和,然后用该总和除以每一位数。
其次,由于要求是O(n)的算法,所以分别求数组b中的每一个元素也不可能,那样话,要O(n^2)的时间复杂度。
所以需要一些技巧了:
我们来分析一下问题的解的结构:
b[0] = (a[1] * a[2] * a[3] * a[4] * a[5] * a[6] * ……)
b[1] = (a[0]) * (a[2] * a[3] * a[4] * a[5] * a[6] * ……)
b[2] = (a[0] * a[1]) * (a[3] * a[4] * a[5] * a[6] * ……)
b[3] = (a[0] * a[1] * a[2]) * (a[4] * a[5] * a[6] * ……)
b[4] = (a[0] * a[1] * a[2] * a[3]) * (a[5] * a[6] * ……)
b[5] = (a[0] * a[1] * a[2] * a[3] * a[4]) * (a[6] * ……)
……
观察以上式子,可以发现:
这里写图片描述
b数组中的每一个元素就是a数组的一个前缀积乘以一个后缀积,所以预处理出a数组的前缀积以及后缀积即可O(n)求出b数组
【AC代码】:

/**
 * 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 * res = (int *)malloc(sizeof(int) * numsSize);
    res[0] = res[1] = nums[0];
    for(int i = 2; i < numsSize; i++){
        res[i] = res[i - 1] * nums[i - 1];
    }
    int index = numsSize - 1;
    int temp_pro = nums[index--];
    for(int i = numsSize - 2; i >= 1; i--){
        res[i] *= temp_pro;
        temp_pro *= nums[index--];
    }
    res[0] = temp_pro;
    *(returnSize) = numsSize;
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值