博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Multiplication of numbers
阅读量:7215 次
发布时间:2019-06-29

本文共 1218 字,大约阅读时间需要 4 分钟。

Questin:

There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. Solve it without division operator and in O(n).

For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1].

Example:

A: {4, 3, 2, 1, 2}

OUTPUT: {12, 16, 24, 48, 24}

思路:

可以使用迭代累计。把output[i]=a[i]左边的乘积 x a[i]右边的乘积,所以,我们可以分两个循环,第一次先把A[i]左边的乘积放在Output[i]中,第二次把A[i]右边的乘积算出来;也可以直接放在一个循环中,只不过需要同时计算左边的乘积和右边的乘积。(当然也可分开计算A[i]左边和右边的数据,这样容易理解!最后将左边和右边的相乘即可

代码如下:

void Multiplication_Array(int A[], int OUTPUT[], int n) {  int left = 1;  int right = 1;  for (int i = 0; i < n; i++)      OUTPUT[i] = 1;  for (int i = 0; i < n; i++) {      OUTPUT[i] *= left;      OUTPUT[n - 1 - i] *= right;      left *= A[i];      right *= A[n - 1 - i];  }}
void Mutiplication_Array2() {
    int *X = new int[n];
    int *Y = new int[n];
    // Create X
    X[0] = 1;
    for(int i = 1; i < n; i++){
        X[i] = X[i-1] * A[i-1];
    }
    // Create Y
    Y[n-1] = 1;
    for(int i = n-2; i >= 0; i--){
        Y[i] = Y[i+1] * A[i+1];
    }
    // Create Out
    for(int i = 0; i < n; i++){
        out[i] = X[i] * Y[i];
    }
    // Delete X and Y
    delete[] X;
    delete[] Y;
}

转载地址:http://cmuym.baihongyu.com/

你可能感兴趣的文章
一文盘点MWC 2019所有5G设备和研发进展
查看>>
【leetcode】85. Maximal Rectangle 0/1矩阵的最大全1子矩阵
查看>>
网站真分页js代码该怎么写?
查看>>
教你五分钟入门使用html5 svg绘制图形
查看>>
vue-concise-slider vue滑动组件
查看>>
ElectronOCR:基于Electron+React+Tesseract的MACOS下的OCR工具
查看>>
Mysql 架构及优化之-定时计划任务
查看>>
不插即用!配备微信网页授权模块的CodeIgniter应用脚手架
查看>>
HBase存储剖析与数据迁移
查看>>
人工智能高考511分,未来有望考上东京大学!
查看>>
O2O业务都跳不出这五大领域
查看>>
呼之欲出的量子计算机和漫长的最后一公里
查看>>
“九”答不可 | 量子保密,完美无缺?
查看>>
VMware备份研究
查看>>
dotnet调用node.js写的socket服务(websocket/socket/socket.io)
查看>>
Nibiru Open Day,OZO 遇见 DigiArtist 国际数字艺术展
查看>>
MySQL · 引擎分析 · InnoDB行锁分析
查看>>
ARKit应用超300万次安装,排第一的是一款养成游戏
查看>>
C++ 对引用的深入理解
查看>>
vuejs v-for指令
查看>>