给定的整数的数组,除了其中一个元素出现一次,剩余每个元素出现两次。找出单独出现的这个元素。
你应该有一个线性时间复杂度的算法。你能实现它,而无需使用额外的内存?
we use bitwise XOR to solve this problem :
first , we have to know the bitwise XOR in java
1、0 ^ N = N
2、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
public int singleNumber(int[] nums) {
int ans =0;
int len = nums.length;
for(int i=0;i!=len;i++)
ans ^= nums[i];
return ans;
}
用异或的解法,牛逼
其他解法
public class Solution {
public int singleNumber(int[] nums) {
int count=1;
int a=0;
Map<Integer,Integer> map=new HashMap();
for(int num:nums){
if(!map.containsKey(num)) map.put(num,count);
else map.put(num,count+1);
}
Set<Integer> ks = map.keySet();
Iterator<Integer> it = ks.iterator();
while (it.hasNext()) {
Integer key = it.next();
if(map.get(key)==1) a=key;
}
return a;
}
}