码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-21 21:08:48      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:div   void   hash   public   class   面试题   find   hashmap   整型   

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

方法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:

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

标签:div   void   hash   public   class   面试题   find   hashmap   整型   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!