一、解决方法
解法1:运用异或的方式
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++)
result ^= nums[i];
return result;
}
解法2:运用HashSet的方式
class Solution {
public int singleNumber(int[] nums) {
Set<Integer> set =new HashSet<Integer>();
for(int a: nums){ //从头到尾遍历
if(!set.add(a)){ //如果添加不进set集合(因为里面已经有了一个元素)
set.remove(a);
}
}
Object[] array = set.toArray(); //把集合中的元素放入数组中
return (int)array[0]; //获取数组中第一个元素
}
}
二、相关复习点
1、异或运算
1^1=0;
1^0=1;
0^1=1;
0^0=0;
2、set集合
2.1概述
- Set是一个不包含重复数据的Collection
- Set集合中的数据是无序的(因为Set集合没有下标)
- Set集合中的元素不可以重复 – 常用来给数据去重
2.2Set集合的特点
- 数据无序且数据不允许重复
- HashSet : 底层是哈希表,包装了HashMap,相当于向HashSet中存入数据时,会把数据作为K,存入内部的HashMap中。当然K仍然不许重复。
- TreeSet : 底层是TreeMap,也是红黑树的形式,便于查找数据
2.3Set集合常用方法--用Collection中的方法
2.4HashMap扩容
成长因子:
static final float DEFAULT_LOAD_FACTOR = 0.75f;