Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
题意:数组中只有2个元素只出现了1次,其他元素都出现了2次,请找出这2个元素。
自然联想到使用HashMap,元素值作为Key,出现的次数作为Value,只要找到Value为1的key就好了。
下面贴代码:
public class Solution {
public int[] singleNumber(int[] nums) {
int[] a1 = new int[2];
int k = 0;
HashMap<Integer,Integer> h = new HashMap<>();
for(int a : nums){
if(h.containsKey(a)){ //若已存在,value加1
h.put(a,h.get(a)+1);
}else{ //若不存在,添加
h.put(a,1);
}
}
for(Map.Entry m:h.entrySet()){ //遍历hashmap中的键值对
if((int)m.getValue()==1){
a1[k++] = (int)m.getKey();
}
}
return a1;
}
}
解法中使key存在的value加1的语句为 h.put(a,h.get(a)+1);如果大家有更好的可以在下方留言,非常感谢。
另外遍历hashmap中的键值对使用的是entrySet()方法,我们看一下API中该方法:
返回的是一个Set,元素类型是Map.Entry。其中,Entey是hashmap中的一个静态内部类,用来存放键值对的,在Entry中的我们可以使用getValue和getKey方法来取得键值对中的值和键。