剑指offer题解--⑥数组中只出现一次的数字

数组中只出现一次的数字

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

题目描述

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

题目分析

该题是除了一个数字,其他数字都出现两次的变种;那个可以利用异或的特性(a ^ a = 0 ,b ^ 0 = b),求出解;
这里应该也可以利用特性来求解,但是没想到怎么搞,所以就用最原始的方式,利用map的特性,求出value为1
的两个,再放回到数组中;

代码演示

    public static void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            if (map.get(array[i]) == null){
                map.put(array[i],1);
            }else{
                map.put(array[i],map.get(array[i]) +1);
            }
        }
        List<Integer> result = new ArrayList<>(2);
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            if (integerIntegerEntry.getValue() == 1) {
                result.add(integerIntegerEntry.getKey());
            }
        }
        num1[0] = result.get(0);
        num2[0] = result.get(1);

    }
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务