Created
May 24, 2020 21:21
-
-
Save misterpoloy/5658d550b2ac6d26d87110a4356bd456 to your computer and use it in GitHub Desktop.
#CodeChallenge Longest continues range from start to end in an array
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> | |
#include <climits> | |
using namespace std; | |
vector<int> largestRange(vector<int> array) { | |
vector<int> longestRange; | |
unordered_map<int, bool> arrayMap; | |
int longestLength = INT_MIN; | |
// Inicializate to true for start counting; | |
for (int numb : array) { | |
arrayMap[numb] = true; | |
} | |
for (int numb : array) { | |
// Don't check for alreadychecked numbers | |
if (arrayMap[numb] == false) continue; | |
arrayMap[numb] = false; | |
// If exist increment the left one value | |
int left = numb - 1; | |
int right = numb + 1; | |
int currentLength = 0; | |
while (arrayMap.find(left) != arrayMap.end()) { | |
arrayMap[left] = false; | |
currentLength++; | |
left--; | |
} | |
while (arrayMap.find(right) != arrayMap.end()) { | |
arrayMap[right] = false; | |
currentLength++; | |
right++; | |
} | |
if (longestLength < currentLength) { | |
longestLength = currentLength; | |
longestRange = { left + 1, right - 1 }; | |
} | |
} | |
return longestRange; | |
} |
Author
misterpoloy
commented
May 24, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment