前言
一个整型数组里除了两个数字只出现一次,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
一、解法1:哈希表
-
代码思路:
- step 1:创建一个哈希表
- step 2:当数组元素没有在哈希表中成为key的时候,put进哈希表,当已存在的时候,则remove掉。
- step 3:最后哈希表中剩下的key就是只出现一次的数字
- step 4:遍历key然后返回结果
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
int[] res = new int[2];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i : array){
if(map.containsKey(i)){
map.remove(i);
}else{
map.put(i,null);
}
}
int i = 0;
// 最后拿出来放进返回结果的数组中进行返回
for(Integer num : map.keySet()){
res[i++] = num;
}
return res;
}
}
关于HashMap常见用法的介绍: HashMap:常见用法总结