4.只出现一次的数字II
方法一:使用哈希表
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i],map.getOrDefault(nums[i],0) + 1);
}
int ans = 0;
for(int key : map.keySet()){
if(map.get(key) == 1){
ans = key;
}
}
return ans;
}
}
方法二:位运算
class Solution {
public int singleNumber(int[] nums) {
int[] count = new int[32];
for(int num : nums){
for(int j =0;j<32;j++){
//获取的是二进制数字的最后一位,所以依次从最后一位到第一位
count[j] += num & 1;
num >>>= 1;
}
}
int res = 0,m = 3;
for(int i = 0;i< 32;i++){
res <<= 1;
res |= count[31-i] % m; //恢复第i位的值到res中
}
return res;
}
}