题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
http://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
主要使用了hashmap和arraylist排序。向hashmap 中添加元素,如果hashmap中有该元素,出现两次,从hashmap中删除该元素。最后遍历一遍后hashmap 就剩出现一次的元素。为了最小元素在前面。将hashmap中的元素放到arraylist中进行排序(调用ArrayList的sort方法重写Comparator 接口)。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
ArrayList<Integer> list = new ArrayList<>();
if(array.length==0)
return new int[0];
Map<Integer,Integer> map =new HashMap<>();
for(int i=0;i<array.length;i++){
if(map.containsKey(array[i])){
map.remove(array[i]);
continue;
}else{
map.put(array[i],1);
}
}
for (Integer key:map.keySet()){
list.add(key);
}
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
int[] ints = new int[list.size()];
for(int i=0;i<list.size();i++){
ints[i]=list.get(i);
}
return ints;
}
}
查看16道真题和解析