views:

192

answers:

0

Jessica asked a viral question ( link ):

You're passed an array with n integers in it. Each integer is between 1 and n (inclusive). These numbers are not in sorted order and there may be duplicates or missing numbers.

The problem is to figure out if there are any duplicates in the array in O(n) time and O(1) space without destroying the array.

My question is: Is following algorithm 'correct'?

public static boolean hasDup(int a[]) {
    final int n = a.length, mask = 1 << 31
    int temp, i;
    boolean result = false;

    for (i = 0; i < n; i++) {
        if ((temp = a[i]) < 0)
            temp ^= mask;
        if (a[temp - 1] > 0)
            a[temp - 1] ^= mask;
        else {
            result = true;
            break;
        }
    }
    for (i = 0; i < n; i++) 
        if (a[i] < 0)
            a[i] ^= mask;
    return result;
}