《剑指offer》数组中只出现一次的数字

时间:2021-03-30 14:32:05

题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

解析:直接用set集合去重,每个集合的元素都去原数组array里找,出现一次就保存下

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
import java.util.*;
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
List<Integer> list = new ArrayList<>();
for(int i:array){
list.add(i);
}
LinkedHashSet<Integer> set = new LinkedHashSet<>(list);//去重后的元素集合
int index=0;//标识找到的元素个数
for(Integer i :set){
int count=0;
for(int j:array){
if(j==i){
count++;
}
}
if(index==0){//判断是否找到了第一个元素
if(count==1){//找到了第一个元素只出现一次的数字
num1[0]=i;
index++;
continue;
}
}
if(index==1){//判断是否找到了第二个元素
if(count==1){
num2[0]=i;
return;//第二个都找到了,任务完成,还玩什么,可以返回LOL去了
}
}
}
}
}