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?
我的方法:
public class Solution {
public int singleNumber(int[] A) {
int sum = 0;
HashSet<Integer> hash = new HashSet<Integer>();
for(int i = 0;i < A.length; i++)
{
if(!hash.contains(A[i]))
hash.add(A[i]);
else
hash.remove(A[i]);
}
for(int i = 0;i < A.length; i++){
if(hash.contains(A[i]))
sum = A[i];
}
return sum;
}
}
最好的方法:
public class Solution {
public int singleNumber(int[] A) {
int ans = A[0];
for(int i=1;i<A.length;i++)
{
ans ^= A[i];
}
return ans;
}
}