题目
代码部分一(17ms 26.66%)
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
}
for(int temp : map.keySet()){
if(map.get(temp) == 1)
return temp;
}
return 0;
}
}
-
遍历数组,将数组中的数字分别加入 map ,并记录出现次数
-
遍历 map.keySet() ,找出出现次数为 1 的key,并返回
-
没有符合的则返回0
代码部分二(1ms 99.99%)
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int i = 0; i < nums.length; i++){
res ^= nums[i]; // nums[0] ^= nums[i];
}
return res;
}
}
-
遍历数组,将所有数字进行 ^ (按位异或)
-
在题目条件下,除了特殊数字,其他数字都出现两次,可以相互消去,剩下的数字为所需数字
-
返回 res