Created
January 7, 2018 20:24
-
-
Save jianminchen/7a1a1343458db4a0560cfbceb672238d to your computer and use it in GitHub Desktop.
Array of array products -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
vector<long> arrayOfArrayProducts(const vector<int>& arr) | |
{ | |
// edge case, one element in the array | |
vector<long> res = {}; | |
vector<long> leftProducts(arr.size()); // reduce to one variable [8, 10, 2], leftProduct[3] | |
vector<long> rightProducts(arr.size()); | |
leftProducts[0] = arr[0]; // 1, | |
int length = arr.size(); | |
for(int i = 1; i < length; ++i) { | |
leftProducts[i] = leftProducts[i - 1] * arr[i]; | |
} | |
rightProducts[length-1] = arr[length - 1]; | |
for(int i = arr.size()-2; i >=0; --i) { | |
rightProducts[i] = arr[i] * rightProducts[i+1]; | |
} | |
for(int i = 0; i < length; ++i) { | |
if(i == 0) | |
{ | |
res.push_back(rightProducts[1]); | |
} | |
else if(i == length - 1) | |
{ | |
res.push_back(leftProducts[length -2]); // run out of index ? - | |
} | |
else | |
{ | |
res.push_back(leftProducts[i - 1] * rightProducts[i + 1]); // 3 elements in the array | |
} | |
} | |
// your code goes here | |
return res; | |
} | |
int main() { | |
vector<int> arr = {8,10,2}; | |
vector<long> res = arrayOfArrayProducts(arr); | |
for(auto u : res) | |
cout << u << ' '; | |
return 0; | |
} | |
/* | |
[8, 10, 2] | |
1, 1 * 8. 8 *10 -> 2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment