2014年7月19日土曜日

Lesson 2: MissingIntegers (Missing Integers)

The strategy for this question is to create another array,
and use it as a flag if the value is found or not.

Since we need to find the minimum positive value, we can simply
neglect the negative values. We can also neglect any integer larger
than N, since if we find such a value (larger than N), that means any value between 1 and N may be lacking for sure. 

If all the values between 1 and N is found, that means the minimum positive value lacking is N + 1.

This strategy gives the score of 100%.








--------------------------------
       the solution
--------------------------------

int solution(int A[], int N) 
{
    //prepare the flags
    int* flag = (int*)calloc(sizeof(int), N);
    
    //iterate the given array A.
    int i;
    for (i = 0; i < N; i++){
        //we can neglect the value below 1 or larger than N.
        if (A[i] <= 0 || A[i] > N){
            continue;
        }
        //turn on the flag. this is the zero-indexed array.
        //so give -1 as the offset.
        flag[A[i] - 1] = 1;
    }
    
    //if there is no positive integer lacking between 1 - N,
    //the answer should be N + 1.
    int ans = N + 1;
    //found the minimum integer that is not found in the array A.
    for (i = 0; i < N; i++){
        if (flag[i] == 0){
            //the answer is (the index + 1). (we have -1 offset).
            ans = i + 1;
            break;
        }
    }
    
    //free the allocated memory space.
    free(flag);
    
    return ans;
}

0 件のコメント:

コメントを投稿