MultiplyExceptSelf

本文介绍了一种算法,该算法能在O(n)时间内计算出一个整数列表中每个元素对应的除自身以外所有元素的乘积。通过巧妙地利用两个遍历过程,实现了高效的计算并确保了空间效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a list of integers, your task is to write a program to output an integer-valued list of equal length such that the output element at index 'i' is the product of all input elements except for the input element at 'i'.
 
In other words, let inputArray by an integer array of length 'n'.  The solution,computed into outputArray, would be:
 
for each j from 1 to n-2:
               outputArr[ j ] = inputArray[0] * inputArray[1] * inputArray[2] * ... * inputArray[j-1] * inputArray[j+1] * inputArray[j+2] *...* inputArray[n-1]
for j = 0
               outputArray[0] = inputArray[1] * outputArray[2] * ... * outputArray[n-1]
for j = n-1
               outputArray[n-1] = outputArray[0] * outputArray[1] * outputArray[2] * ... * outputArray[n-2]        
 
As an example, if inputArray = { 1, 2, 3, 4 }, then
 
outputArray = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.
 
Your program should run in O(n) time and should be space efficient.
 
Input format :
 
First line of input contains N , number of elements in list.
Next N lines will each contain an element (a signed integer)
 
Output format :
 
Print the output list of numbers.
 
Sample input :
 
4
5
2
2
3
 
Sample ouput :
 
12
30
30
20
 
Constraint :

 

You may assume that:
 
 - The input array size will always have at least two elements in it, that is, n >= 2.
 - The product of any subset of the input will never exceed the value of a 64 bit integer.
 - The maximum length of input array is 1000.
 1 #include <iostream>
 2 using namespace std;
 3 
 4 bool GetOutputArray(long long * outputArray, const long long * inputArray, const int & size)
 5 {
 6     if(NULL == outputArray || NULL == inputArray || size <= 0)
 7         return false;
 8     outputArray[0] = 1;
 9     for(int i = 1; i < size; ++i)
10         outputArray[i] = outputArray[i-1] * inputArray[i-1];
11     outputArray[0] = inputArray[size-1];
12     for(int j = size-2; j > 0; --j)
13     {
14         outputArray[j] *= outputArray[0];
15         outputArray[0] *= inputArray[j];
16     }
17     return true;
18 }
19 int main()
20 {
21     int N;
22     while(cin >> N)
23     {
24         long long * inputArray = new long long[N];
25         long long * outputArray = new long long[N];
26         for(int i = 0; i < N; ++i)
27             cin >> inputArray[i];
28         GetOutputArray(outputArray, inputArray, N);
29         for(int j = 0; j < N; ++j)
30             cout << outputArray[j] << endl;
31         delete inputArray;
32         delete outputArray;
33     }
34     return 0;
35 }

 

转载于:https://www.cnblogs.com/xubin0523/archive/2012/09/20/2695846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值