• 剑指offer四十之数组中只出现一次的数字


    一、题目

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

    二、思路

        建一个hashMap,统计各数字出现的次数,然后遍历hashMap,输出出现一次的数字。

    三、代码

    //num1,num2分别为长度为1的数组。传出参数
    //将num1[0],num2[0]设置为返回结果
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Solution {
        public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
            
            if(array==null||array.length==0){
                return;
            }
            
            //新建hashMap,统计字数出现的次数
            HashMap<Integer,Integer> hashMap=new HashMap<Integer, Integer>();
    
            //存储字符出现一次的数
            int[] num=new int[2];
            //统计每个字符的次数
            for(int key:array){
                if(hashMap.containsKey(key)){
                    hashMap.put(key,hashMap.get(key)+1);
                }else {
                    hashMap.put(key,1);
                }
            }
    
            //遍历,如果出现次数为1,则将改数保存到数组num中
            int i=0;
            Set<Map.Entry<Integer,Integer>> set=hashMap.entrySet();
            for(Map.Entry<Integer,Integer> s:set){
                if(s.getValue()==1){
                    num[i]=s.getKey();
                    i++;
                }
            }
    
            //保存结果
            num1[0]=num[0];
            num2[0]=num[1];
        }
    }
    View Code

    ---------------------------------------------

    参考链接:

    https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  • 相关阅读:
    影视-纪录片:《梵净山》
    NuGet:ServiceStack
    资源-产品:ServiceStack
    Win7x64安装Oracle11201x64 解决PLSQL Developer无法找到oci问题
    Oracle11g环境设置-windows环境
    安装sql server提示挂起报错
    安装oracle11g未找到文件WFMLRSVCApp.ear文件
    配置linux中文
    卸载rpm包提示:error: specifies multiple packages
    FileZilla简单介绍及运用
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/7658182.html
Copyright © 2020-2023  润新知