Question
Solution
思路:构造一个map,遍历数组记录每个数出现的次数,再遍历map,取出出现次数为1的num
public int singleNumber(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int i=0; i<nums.length; i++) {
Integer count = countMap.get(nums[i]);
if (count == null) {
count = 0;
}
countMap.put(nums[i], count + 1);
}
int num = -1;
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
num = entry.getKey();
break;
}
}
return num;
}