找出数组中不同的两个数

来源:互联网 发布:nginx 点播服务器 编辑:程序博客网 时间:2024/06/10 15:12
  • 题目:数组中除了两个数与数组中任何数都不同,剩下的数两两相同,找出这两个不同的数。要求时间复杂度为O(n),空间复杂度为O(1)
/** * 在数组中找出不相同的两个数 * @author Rose * */public class TwoDiffOfArr {    public static void main(String[] args) {        getDiffNum(new int[]{1,4,5,2,5,4});    }    private static void getDiffNum(int[] array){        if(array == null || array.length < 2)            return;        //0和数组中的数两两xor,得到的结果是不同的两位数的抑或结果        int m = 0;        for (int i = 0; i < array.length; i++)             m ^= array[i];        int reslut1 = 0;        int result2 = 0;        //将两数亦或的结果转为二进制数        String binaryInteger = Integer.toBinaryString(m);        //找到二进制数中最后一位为1的位置        int index = binaryInteger.length() - (binaryInteger.lastIndexOf("1")+1);        //将数组中的数按照index位是否为1分为两组,0和每组的数字两两xor,最后的值就是不同的数        for (int i = 0; i < array.length; i++) {            if(((array[i] >> index) & 1) == 1)                reslut1 ^= array[i];            else                result2 ^= array[i];        }        System.out.println("不同的两个数是:" + reslut1 +" " + result2);    }}