【剑指offer】_16 构建乘积数组
生活随笔
收集整理的這篇文章主要介紹了
【剑指offer】_16 构建乘积数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給定一個數組A[0,1,…,n-1],請構建一個數組B[0,1,…,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
解題思路
設有數組大小為5。
對于第一個for循環
第一步:b[0] = 1; 第二步:b[1] = b[0] * a[0] = a[0] 第三步:b[2] = b[1] * a[1] = a[0] * a[1]; 第四步:b[3] = b[2] * a[2] = a[0] * a[1] * a[2]; 第五步:b[4] = b[3] * a[3] = a[0] * a[1] * a[2] * a[3];對于第二個for循環
第一步
temp *= a[4] = a[4]; b[3] = b[3] * temp = a[0] * a[1] * a[2] * a[4];第二步
temp *= a[3] = a[4] * a[3]; b[2] = b[2] * temp = a[0] * a[1] * a[4] * a[3];第三步
temp *= a[2] = a[4] * a[3] * a[2]; b[1] = b[1] * temp = a[0] * a[4] * a[3] * a[2];第四步
temp *= a[1] = a[4] * a[3] * a[2] * a[1]; b[0] = b[0] * temp = a[4] * a[3] * a[2] * a[1];代碼實現
class Solution { public:vector<int> multiply(const vector<int>& A) {vector<int> res;int length1 = A.size();if(length1 == 0)return res;res.push_back(1);for(int i=1;i<length1;++i)res.push_back(res[i-1]*A[i-1]);double temp =1;for(int i=length1-1;i>=0;--i){res[i]= res[i]*temp;temp*=A[i];}return res;} }; 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【剑指offer】_16 构建乘积数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【剑指offer】_15数组中重复的数字
- 下一篇: 缔造者堆智力还是独立啊