MultiplyExceptSelf

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 }

 

posted @ 2012-09-20 19:59  可乐爱上了雪碧  阅读(208)  评论(0编辑  收藏  举报