数组中数字出现的次数
题目:
在一个数组
nums
中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。
思路:
HashMap键值对<存放的数字,该数字出现的次数>
题解:
class Solution {
public int singleNumber(int[] nums) {
//hashmap K 存数字 V存次数
int res = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for (int num :
nums) {
if (!map.containsKey(num)){
map.put(num,1);
continue;
}
map.put(num,map.get(num)+1);
}
for (Map.Entry<Integer,Integer> entry :
map.entrySet()) {
if (entry.getValue() ==1){
res = entry.getKey();
break;
}
}
return res;
}
}