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?
解法一:(HashSet)
import java.util.Hashtable;
public class Solution {
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i:nums){
if(!set.add(i))
set.remove(i);
}
Iterator<Integer> it = set.iterator();
return it.next();
}
}
解法二:(位操作)
public class Solution {
public int singleNumber(int[] nums) {
int c = 0;
for (int i = 0; i < nums.length; i++)
{
c = c ^ nums[i];
}
return c;
}
}