剑指offer试题编程练习36(java) 找出数组中只出现一次的数字

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

思路:利用Map数据结构来进行处理,熟悉Map数据结构怎么存取数据。

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
import java.util.Map;
import java.util.HashMap;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        //利用map结构来存储相应的元素及其出现的次数
        int len = array.length;
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<len;i++){
            if(!map.containsKey(array[i])){
                map.put(array[i],1);
            }else{
                map.put(array[i],map.get(array[i])+1);
            }
        }
        int count=1;
        for(Integer key : map.keySet()){
            if(map.get(key)==1){
                if(count==1){
                    num1[0] = key;
                    count++;
                }else{
                    num2[0] = key;
                    break;
                }
            }
        }
    }
}
发布了49 篇原创文章 · 获赞 0 · 访问量 804

猜你喜欢

转载自blog.csdn.net/weixin_41881277/article/details/105453702
今日推荐