Created
May 20, 2020 02:55
-
-
Save misterpoloy/15452d1caaff8090a7cae475e4e98bd6 to your computer and use it in GitHub Desktop.
Four number Sum #CodeChallenge
This file contains hidden or 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 <vector> | |
#include <unordered_map> | |
using namespace std; | |
vector<vector<int>> fourNumberSum(vector<int> array, int targetSum) { | |
// Write your code here | |
unordered_map<int, vector<vector<int>>> allPairSums; | |
vector<vector<int>> quadruplets{}; | |
// For every element apply the next algorithm | |
// We can skip the first number and the last, we need 1 padding for left and right | |
// And since we think in therms o pais, its fine. | |
for (int i = 1; i < array.size() - 1; i++) { | |
// Agregar números que ya existan | |
for (int j = i + 1; j < array.size(); j++) { | |
int currentSum = array[i] + array[j]; | |
int difference = targetSum - currentSum; | |
// Derecha -> Solo si ya existe el par guardado, para evitar duplicados | |
if (allPairSums.find(difference) != allPairSums.end()) { | |
// (*) Explicación: Es posible que haya muchos pares para el mismo arreglo. | |
for (vector<int> pair : allPairSums[difference]) { | |
pair.push_back(array[i]); | |
pair.push_back(array[j]); | |
quadruplets.push_back(pair); | |
} | |
} | |
} | |
// Luego si no existen si los agrega. | |
// Ahora, si puedes agregar si no existe, Si existe crea el quadruplet | |
for (int k = 0; k < i; k++) { | |
int currentSum = array[i] + array[k]; | |
if (allPairSums.find(currentSum) == allPairSums.end()) { | |
// Sino existe, crealo | |
allPairSums[currentSum] = vector<vector<int>>{{ array[k], array[i]}}; | |
} else { | |
// Si existe, agrega el Pa | |
allPairSums[currentSum].push_back(vector<int>{ array[k], array[i]}); | |
} | |
} | |
} | |
return quadruplets; | |
} |
Author
misterpoloy
commented
May 20, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment