[Offer] [56-1] [array appears only once in two digits]

Title Description

  An array of integers in addition to the two figures, other figures appear twice. Please write a program to find these two figures appear only. Required time complexity is O (n), the spatial complexity is O (1).

Cattle brush off questions address network

Ideas analysis

  1. If this title was changed to a number appears only once, there were two other numbers, then we can use different ways or will all the numbers XOR, the results finally obtained it appeared only once for the numbers, because duplicate numbers XOR operation will cancel out each;
  2. We can talk about an array divided into two groups, each group meet the above conditions, grouped as follows:
  3. All the numbers to get exclusive resultExcuOR or later, the XOR result in at least a binary 1, we find the first position 1, denoted by n bits; n-th digit is 1 for the standard the array are grouped, grouping the results obtained in compliance with a condition;

Test Case

  1. Functional test: how an array of digital duplicate; array no duplicate numbers.

Java code

public class Offer056_01 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
        Solution1(array,num1,num2);
    }

    

    private static void Solution1(int[] array, int[] num1, int[] num2) {
        if(array==null || array.length<2){
            return;
        }
        int resultExcuOR = 0;
        for(int i=0;i<array.length;i++){
            resultExcuOR ^= array[i];
        }
        int indexOf1 = 0;
        while( ((resultExcuOR&1)==0) && indexOf1<=4*8){ 
            resultExcuOR = resultExcuOR>>1;
            indexOf1++;
        }
        
        num1[0]=0;
        num2[0]=0;
        for(int i=0;i<array.length;i++){
            if(isBit1(array[i],indexOf1)){
                num1[0] ^= array[i];
            }else{
                num2[0] ^= array[i];
            }
        }
    }

    private static boolean isBit1(int num, int indexOf1) {
        num = num>>indexOf1;
        return (num&1)==1;
    }
    
    private static void test1() {

    }
    private static void test2() {

    }

    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer561-shu-zu-zhong-zhi-chu-xian-yi-ci-de-liang-.html