题意: 在一个非空数组中,找出只出现了一次的数字 ( 其他的均出现了两次 )
第一种、 map
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) {
map.remove(nums[i]);
}else {
map.put(nums[i], nums[i]);
}
}
int res = 0;
for ( Integer k : map.keySet() ) {
res = map.get(k);
}
return res;
}
}
set
class Solution {
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if(set.contains(nums[i])) {
set.remove(nums[i]);
}else {
set.add(nums[i]);
}
}
return (int)set.toArray()[0];
}
}
第二种、异或 ⭐
思路: 位运算
两个相同的数字异或,结果为0
和 0 异或的数字 == 它本身
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res ^ nums[i];
}
return res;
}
}
第三种、数学
思路: 因为每个数字均出现两次,只有一个出现一次.
公式: 2*(a+b+c) - (a+a+b+b+c) = c