[codility]Perm-Missing-Elem

来源:互联网 发布:网络机顶盒看不了电视 编辑:程序博客网 时间:2024/06/06 08:57
// 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;}

原创粉丝点击