使用map的方法:
class Solution {
public int singleNumber(int[] nums) {
//数组中一个数字出现一次,剩下的数字都出现了三次,要找到那个只出现一次的数字
//首先想到的是map记录每个数出现多少次。
if(nums==null || nums.length==0){
return 0;
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int temp:nums){
if(map.containsKey(temp)){
map.put(temp,2);
}else{
map.put(temp,1);
}
}
for(int temp:nums){
if(map.get(temp)==1){
return temp;
}
}
return 0;
}
}
使用位运算的方法:
一个长32的数组(因为int 4byte,32位),遍历数组中的每个元素,把他们的每一位储存进数组中。最后得到的数组中元素%3,再或运算与0000000000... 拼接起来得到的就是所求数啦。这个方法比较简单,时间n 空间1(恒定大小的数组)。
class Solution {
public int singleNumber(int[] nums) {
int[] counts = new int[32];
for(int num : nums) {
for(int j = 0; j < 32; j++) {
counts[j] += num & 1;
num >>>= 1;
}
}
int res = 0, m = 3;
for(int i = 0; i < 32; i++) {
res <<= 1;
res |= counts[31 - i] % m;
}
return res;
}
}