// 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 发布
本文介绍了一种使用深度优先搜索类似的方法来寻找数组中缺失的元素的算法。通过遍历数组并调整元素位置,最终确定缺失的数值。适用于需要查找未出现在正确位置上的元素的场景。

279

被折叠的 条评论
为什么被折叠?



