Find an integer that appears exactly once in an array of unsorted integers in Java

I was given an unsorted array of integers, where each integer is displayed exactly twice, excluding one integer that appears only once. I would like to write a program in Java that finds an integer that appears only once.

Here is my attempt:

int findIntegerThatOccursOnce(int[] arr)
{
    HashSet<Integer> hashSet = new HashSet<Integer>();
    int mSum = 0;
    for(int i = 0; i < arr.length; i++)
    {
        if(hashSet.contains(arr[i]))
        {
          mSum = mSum - arr[i];
        }
        else
        {
          hashSet.add(arr[i]);
          mSum = mSum + arr[i];
        }
    }
    return mSum;
}

My professor said it was a good attempt, but there is a better one that uses less space, but I don’t see how I can do this with less space? Can someone help explain the problem of space?

+4
source share
2 answers

, , , xor . ,

static int findIntegerThatOccursOnce(int[] arr) {
    int v = 0;
    for (int i : arr) {
        v ^= i;
    }
    return v;
}
+1

O (n) O (n), , , "", , .

, , , Exclusive (XOR) ; , , .

, . O (1).

0

Source: https://habr.com/ru/post/1678303/


All Articles