题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
参考思路
思路一
最常用的思路就是使用一个Map来存储每一个数字出现的次数,最后遍历Map来找出只出现一次的数字。
import java.util.Map;
import java.util.HashMap;
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i:array){
if(map.containsKey(i)){
int numKey = map.get(i);
map.put(i,++numKey);
}
else{
map.put(i,1);
}
}
int count = 0;
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
int value = entry.getValue();
if(value == 1){
if(count == 0){
count++;
num1[0] = entry.getKey();
}
if(count == 1){
num2[0] = entry.getKey();
}
}
}
}
}
思路二
使用Arrays.sort 对数组排序,使用栈进行从小到大入栈,一样的则都弹出,不一样则入栈,最后观察栈中留下来的元素则是只出现一次的元素。
import java.util.Arrays;
import java.util.Stack;
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
Arrays.sort(array);
Stack<Integer>sta = new Stack<Integer>();
for(int i=0; i<array.length; i++){
if(sta.empty() || sta.peek()!=array[i]) {
sta.push(array[i]);
}else if(sta.peek() == array[i]) {
sta.pop();
}
}
num1[0] = sta.pop();
num2[0] = sta.pop();
}
}