The problem;
"return first positive integer that doesn't appear in vector"
My code below works for my test cases. However codility says Im only 40% correct (without giving reasons)
Here's my code, I dont see input arrays where this doesn't work.
/* return first non negative number that doesn't appear in vector e.g. -1,-4, 1, 3 ,2, 9, 10 -> return 4
e.g 1, 1, 2, 3, 4 -> returns 5
1) sort => -1 , -4, 1, 2, 3, 9 , 10 find first non negative number, ignore negatives. If all negatives , return 1;
iterate starting from result of find_if 1 above.
iterate until end or the next number is not next number e.g. 1,2,3,5 will stop at 3
add 1 to get the smallest positive value not in input.
*/
int solution(vector<int>& A) {
// I have a feeling max(int) is in play, the question doesn't specify what to do when
// input = { 0,1,2,3,4 ... std::numeric_limits<int>::max() }
cout << "Max int is " << std::numeric_limits<int>::max() << endl;
std::sort(A.begin(), A.end());
auto iter = find_if(A.begin(), A.end(), [=](int i)
{
return (i > 0);
});
if (iter == A.end())
{
return 1;
}
int result = *iter;
while (iter < A.end() && ((*iter - result) < 2))
{
result = *iter;
++iter;
}
result += 1;
return result;
}