剑指 Offer 66 构建乘积数组

给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法

标签:剑指 Offer发布于:编辑于:浏览量:1584

概述

https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/

不能使用除法。

暴力解

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        vector<int> ans = a;
        for (int i = 0; i < a.size(); i ++) {
            ans[i] = 1;
            for (int j = 0; j < a.size(); j ++) {
                if (i != j) ans[i] *= a[j];
            }
        }
        return ans;
    }
};

O(n^2) 时间复杂度。

TLE 了。

前缀积和后缀积

O(n) 的时间复杂度。

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        vector<int> pre = a;
        vector<int> post = a;
        for (int i = 1; i < a.size(); i ++) {
            pre[i] = pre[i-1] * a[i];
        }
        for (int i = a.size() - 2; i >= 0; i --) {
            post[i] = post[i+1] * a[i];
        }
        vector<int> ans = a;
        for (int i = 0; i < a.size(); i ++) {
            int preProduct = 1;
            if (i != 0) preProduct = pre[i-1];
            int postProduct = 1;
            if (i != a.size() - 1) postProduct = post[i+1];
            ans[i] = preProduct * postProduct;
        }
        return ans;
    }
};