题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
http://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
Map<Integer,Integer> hashmap = new HashMap<>();
for(int i = 0 ; i < array.length ; i++){
if (hashmap.containsKey(array[i])){
hashmap.put(array[i],hashmap.get(array[i])+1);
}else{
hashmap.put(array[i],1);
}
}
int[] res = new int[2];
int cnt = 0;
for(Integer key : hashmap.keySet()){
if (hashmap.get(key)==1 ){
res[cnt]=key ;
cnt++;
}
}
return res;
}
}
1、用hashmap来处理这个问题,用key来存数组的数,如果出现一次,就在value值上+1。 2、最后用keySet()来遍历,输出value=1的值就是那个数了。