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?
source
share