算法:数组中出现一次的数字

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
本题有多种解法,此处用hashMap的方法,方法步骤如下:

 1. HashMap中的键存储数组array的数字,值存储array中的数值出现的个数
 2. 遍历HashMap,找到Value值等于1的键,并将其储存在新数组temp中
 3. 将数组temp里面的值赋值给num1,num2.其代码如下
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<array.length;i++){
            if(map.containsKey(array[i])){
                int len=map.get(array[i]);
                map.put(array[i],len+1);
            }else{
                map.put(array[i],1);
            }
        }
        int[] temp=new int[2];
        int index=0;
        Set<Map.Entry<Integer, Integer>> sm=map.entrySet();
        for (Map.Entry<Integer, Integer> entry : sm) {
            int t1=entry.getKey();
            int t2=entry.getValue();
            if(t2==1){
                temp[index++] = t1;
            }
        }
        num1[0]=temp[0];
        num2[0]=temp[1];
    }
}
持续更新中。。。。

猜你喜欢

转载自blog.csdn.net/weixin_46535360/article/details/108430859