The problem:
Given an array of integers, every element appears twice except for one. Find that single one.
Java Solution 1
The key to solve this problem is bit manipulation. XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.
public int singleNumber(int[] A) { int x = 0; for (int a : A) { x = x ^ a; } return x; } |
Java Solution 2
public int singleNumber(int[] A) { HashSet<Integer> set = new HashSet<Integer>(); for (int n : A) { if (!set.add(n)) set.remove(n); } Iterator<Integer> it = set.iterator(); return it.next(); } |
The question now is do you know any other ways to do this?
Java 8 version for XOR method.
public static int singleNumber8(int[] elements)
{
return Arrays.stream(elements).reduce(0,(a, b) -> a ^ b);
}
public int singleNumber(int[] A){
List list=Arrays.stream(A).boxed().collect(Collectors.toList());
int number=0;
for(int i=0;i<A.length;i++){
if(Collections.frequency(list, A[i])==1){
number=A[i];
}
}
return number;
}
no extra space dude
it.hasNext will return the boolean value and method signature is having int as output
XOR is associative: x ^ (y ^ z) == (x ^ y) ^ z
u r rite .. 🙂
‘Every element appears twice except for one’
Have you unit tested it … this does not work …for eg int arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}; output should be 2 …
This is wat I came up with:
public static int singleNumber(int[] numbers)
{
if(numbers == null)
throw new NullPointerException(“Parameter numbers cannot be null.”);
if(numbers.length == 0)
throw new IllegalArgumentException(“Parameter numbers cannot be empty.”);
Set oddNumbers = new HashSet();
for(int i=0; i<numbers.length; i++) {
int number = numbers[i];
if(oddNumbers.contains(number))
oddNumbers.remove(number);
else
oddNumbers.add(number);
}
if(oddNumbers.size() != 1)
throw new IllegalArgumentException("Parameter number does not contain a single number.");
return oddNumbers.iterator().next();
}
nice solution . better than using map like I did.
minus
a linear but not so fast alg: using hash table.