码迷,mamicode.com
首页 > 编程语言 > 详细

《剑指offer》第六十六题:构建乘积数组

时间:2020-04-14 00:42:37      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:初始   cst   product   个数   put   style   bsp   构建   二维   

// 面试题66:构建乘积数组
// 题目:给定一个数组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]。不能使用除法。

#include <cstdio>
#include <vector>

using namespace std;
//把B[i]看成[=A[0],A[1],… ,A[i-1],1,A[i+1],…,A[n-1]]
//对于B,就成了二维数组,对于1左面是上三角矩阵,右面是下三角矩阵
//三角矩阵的每行乘积值计算可以从顶向下
void BuildProductionArray(const vector<double>& input, vector<double>& output)
{
    int length1 = input.size();
    int length2 = output.size();

    if (length1 == length2 && length2 > 1)
    {
        output[0] = 1;
        for (int i = 1; i < length1; ++i)
        {
            output[i] = output[i - 1] * input[i - 1];//计算左面上三角矩阵的每行乘积值
        }

        double temp = 1;
        for (int i = length1 - 2; i >= 0; --i)//注意两个循环的i初始化值
        {
            temp *= input[i + 1];//计算下三角矩阵的每行乘积值
            output[i] *= temp;//上下三角的同行乘机值再相乘,就是满足题意的B[i]值了
        }
    }
}

 

《剑指offer》第六十六题:构建乘积数组

标签:初始   cst   product   个数   put   style   bsp   构建   二维   

原文地址:https://www.cnblogs.com/ZSY-blog/p/12695113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!