一个整数数组中,有两个元素只出现一次,其他所有元素均出现两次。 找出只出现一次的那两个元素。(java实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lilamei170607/article/details/82729284

一个整数数组中,有两个元素只出现一次,其他所有元素均出现两次。 找出只出现一次的那两个元素。

思路大概是这样的:因为除了这两个只出现一次的数字外,其余都是成对出现的,有一种运算符,异或运算,两个相同的数字异或之后为0,所以将数组中所有的数字依次异或,结果就是这个两个支出现一次的的数异或的结果;接下来就是如何将他们分开,因为这两个数不相同,所以异或的结果必定不为0,找出这个异或的结果的 二进制表示中第一次出现医德位数,按这个条件,将原来的数组分为两个子数组,然后将他们中的数字依次异或即可得到数组中只出现依次的的两个数。

java代码实现:(其中部分借鉴了一下网上的)

public class main {
    public static  int[] fun(int []a){
     int n=0;
     int[] res = new int[2];
     for(int i=0;i<a.length;i++){
         n^=a[i];
     }
     int index = findFirst1(n);
     for(int i = 0; i < a.length; ++i){
         if(isBit1(a[i], index)){
             res[0] ^= a[i];
            }else{
                res[1] ^= a[i];
            }
        }
        return res;
    }
//找出二进制表示中第一个为1的位数
    private static int findFirst1(int bitResult){
        int index = 0;
        while(((bitResult & 1) == 0) && index < 32){
            bitResult >>= 1;
            index++;
        }
        return index;
    }
//对原数组进行分类
    private static boolean isBit1(int target, int index){
        return ((target >> index) & 1) == 1;
    }
    public static void main(String[] args) {
        int[] a = {3, 2, 5, 8, 4, 2, 3, 7, 5, 8};
        for (int n : fun(a)) {
            System.out.println(n);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lilamei170607/article/details/82729284