// you can also use includes, for example:
// #include <algorithm>
int solution(vector<int> &A) {
// write your code in C++98
//enumate each element in the array, if it's not in the right place, then try to fix it using depth first search like method
//, if an element can not be corrected after tuneing then it is the missing element
for(int i = 0; i < A.size(); ++i)
{
int curIdx = A[i]-1;
while(curIdx >= 0 && curIdx < A.size() && A[curIdx] != curIdx+1)
{
int nextIdx = A[curIdx]-1;
A[curIdx] = curIdx+1;
curIdx = nextIdx;
}
}
//get the first incorrect element
for(int i = 0; i < A.size(); ++i)
if(A[i] != i+1) return i+1;
return A.size()+1;
}
[codility]Perm-Missing-Elem
最新推荐文章于 2020-10-27 02:11:15 发布