只出现一次的数字

问题描述:给你一个整型数组,数组中有一个数只出现过一次,其他数都出现了两次,求这个只出现了一次的数。

方法1:求取数组中的最大值 ,创建一个长度为数组中最大的boolean类型的数组,数组开始存储的为true,遍历整形数组,更改与整数相对应的Boolean数组中的值为反值,遍历完成后,boolean类型数组中为false的下标为改数字

方法2:二进制

异或的特点:相同的数异或为0,0和任何数异或还是这个数本身,并且异或支持交换律。  相同为0   不同为1

所有数异或 获得的就是没有重复的数;

    public static Integer getResult(int[] arr){
        int temp=arr[0];
        for(int i=1;i<arr.length;i++){
            temp=temp^arr[i];
        }
        return temp;
        
    }
View Code

如果问题描述改为:给你一个整型数组,数组中有一个数只出现过两次,其他数都出现了一次,求这个出现了两次的数。

方法1:

    public static Integer getResult(int[] arr){
        Set<Integer> set=new HashSet<>();
        for(int i=0;i<arr.length;i++){
            if(!set.add(arr[i])){
                return arr[i];
            }
        }
        return null;
        
    }
View Code
原文地址:https://www.cnblogs.com/xiatc/p/12372143.html