Tuesday, August 7, 2012

Find a missing integer in an array of number

Find a missing integer in an array of number

Case 1: Sorted
Use two pointers to store previous and current value, and difference between two number should equal to 1.
public static int findMissing_Sorted(int[] input){
    if(input.length == 0)
        return 0;

    int prev = input[0];
    for(int i = 1 ; i < input.length ; i++){
        int curr = input[i];
        if((curr - prev) != 1)
            return (prev + 1);
        else
            prev = curr;
    }
    return 0;
}



Case 2: Unsorted
Get the sum of 1 to N, use formula sum = (N+1)*(N)/2
Minus the element in the array, and the remaining value is the missing number.
public static int findMissing_Unsorted(int[] input){
    if(input.length == 0)
        return 0;
   
    int N = 10;
    int max = (N + 1) * N / 2;
  
    for(int i = 0 ; i < input.length ; i++)
        max -= input[i];
   
    return max;
}

No comments: