I have been given an unsorted array of integers where each integer appears precisely twice, excluding one integer which appears only one time. I would like to write a program in Java that finds the 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 cannot see how I can do it with less space? Can anyone help explain about the space issue?