首页 > 编程语言 > 详细

面试题:数组中只出现一次的数字

时间:2018-08-21 20:50:42      阅读:169      评论:0      收藏:0      [点我收藏+]

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

方法1:哈希表

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
import java.util.HashMap;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<array.length;i++){
            Integer key = array[i];
            Integer value = map.get(key);
            if(value!=null){
                map.put(key,value+1);
            }else{
                map.put(key,1);
            }
        }
        int index = 0;
        for(int i=0;i<array.length;i++){
            if(map.get(array[i])==1&&index==0){
                num1[index]=array[i];
                index++;
            }else if(map.get(array[i])==1&&index==1){
                num2[index-1]=array[i];
                break;
            }
        }
    }
}

方法2:

面试题:数组中只出现一次的数字

原文:https://www.cnblogs.com/Aaron12/p/9513782.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!