I'm solving this simple challenge:
Given a vector A with N unique elements greater than 0 and lower or equal than N+1, find the missing element. Example:
A = [1,3,2,5] -> missing number 4
A = [1,3,5,4] -> missing number 2
I've come to the following solution. I'm interested in thoughts and ideas on how to write it as expressive as possible:
Option 1, compact but not very expressive:
int solution_1(std::vector<int> &v) {
sort(v.begin(), v.end());
for (std::size_t i = 0; i < v.size(); ++i) {
if (v[i] != i+1) return i+1;
}
return v.size()+1;
}
Option 2
int solution_2(std::vector<int> &v) {
sort(v.begin(), v.end());
auto missing_element = std::find_if(
v.begin(), v.end(),
[index=1](auto& element) mutable {
if (element != index++) {
return true;
} else {
return false;
}
});
if (missing_element == v.end()) {
return v.size() + 1;
} else {
return *missing_element - 1;
}
}
Any ideas on how to improve this or how to make it more expressive?