问题描述
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解决方法
//复杂度为O(n)
/*
we use bitwise XOR to solve this problem :
first , we have to know the bitwise XOR in java
0 ^ N = N
N ^ N = 0
So..... if N is the single number
N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N
= (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N
= 0 ^ 0 ^ ..........^ 0 ^ N
= N
*/
class Solution
{
public static int singleNumber(int[] nums)
{
int result = 0;
for(int i:nums)
{
result ^= i;
}
return result;
}
}