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

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
 
将所有的数异或,根据得到的结果的最后一位1区分为两部分,再分别异或,得到的两个结果即最后答案
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {//位运算 my
        int result = 0;
        for (int i = 0; i < array.length; i++) {
            result = result ^ array[i];
        }
        int bit = result&(-result);//得到最后一位1
        int n1=0;
        int n2=0;
        for (int i = 0; i < array.length; i++) {
            int s = array[i]&bit;
            if(s== 0 ){
                n1 = n1 ^ array[i];
            }
            else{
                n2 = n2 ^ array[i];
            }
        }
        num1[0] = n1;
        num2[0] = n2;
    }
原文地址:https://www.cnblogs.com/zhacai/p/10711665.html