Sword refers to offer—56. Numbers that appear only once in the array—Analysis and code (Java)

Sword refers to offer-56. Numbers that appear only once in the array-analysis and code [Java]

1. Title

Except for two numbers in an integer array, the other numbers appear twice. Please write a program to find these two numbers that only appear once.

Two, analysis and code

1. Binary split + XOR

(1) Thinking

Combining the characteristics of each number and its own exclusive OR is 0, if only one number appears once in an integer array, and the other numbers appear twice, just add all numbers together to get it.
On this basis, this question can be transformed into how to divide the array into two parts each containing a number that appears only once.
One solution is to XOR all the numbers in the array, and the result is equivalent to the XOR of two numbers that only appear once. Therefore, for the binary digit with 1 in it, for two digits that appear only once, one of them must be 0 and the other is 1. According to this feature, the entire array can be split, and then combined with the XOR method to solve.

(2) Code

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    
    
    public void FindNumsAppearOnce(int [] array, int num1[], int num2[]) {
    
    
        if (array == null || array.length < 2)
            return;
        
        int sum = 0;
        for (int i = 0; i < array.length; i++)
            sum ^= array[i];
        int index = 0;
        while ((sum & 1) == 0) {
    
    
            sum >>= 1;
            index++;
        }
        
        int n1 = 0, n2 = 0;
        for (int i = 0; i < array.length; i++) {
    
    
            if (((array[i] >> index) & 1) == 0)
                n1 ^= array[i];
            else
                n2 ^= array[i];
        }
        num1[0] = n1;
        num2[0] = n2;
        return;
    }
}

(3) Results

Running time: 19ms, occupied memory: 9680k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/111561902