哈希集合
public static int singleNumber(int[] nums) {
int n=nums.length;
Set<Integer> set=new HashSet<>();
set.add(nums[0]);
for (int i=1;i<n;i++){
if (set.contains(nums[i])){
set.remove(nums[i]);
continue;
}
else set.add(nums[i]);
}
return set.hashCode();
}
位运算
public static int singleNumber(int[] nums) {
int index=0;
for (int num:nums){
index^=num;
}
return index;
}
学以致用
- hashCode():适用于这道题,它返回哈希散列值。如果集合中只有9,返回9.如果有9和7,那么返回16.
异或运算^:
- 运算规则:0^0=0; 0^1=1; 1^0=1; 1^1=0;
- 与0运算,保留原值
- 一个数与另一个数异或两次是其本身 :8^ 9^9=8
按位与运算&
- 运算规则:0&0=0; 0&1=0; 1&0=0; 1&1=1;(有零就为零)
- if(((n-1)&n)==0) 符合这样的数都是二的整数次方
按位或运算符(|)
- 运算规则:0|0=0; 0|1=1; 1|0=1; 1|1=1;(有1就为1)