Huawei machine test - find two different numbers in the array

(Advanced) It is known that the numbers in the array are all the same and only two are different. Find these two numbers.

There are also three methods provided here. The first two are similar to the previous ones, and the third requires proficiency in XOR operations.

Solution 1 (high time complexity)

Idea: Two layers of for loops. If a number does not traverse to the same number as itself, record this number. Otherwise, end the loop and continue traversing with the next number.
Time complexity: O( n 2 n^2n2 )
Space complexity: O(1)

Solution 2 (high space complexity)

Idea: Use a dictionary. If the dictionary key does not contain the number, add it to the dictionary. Otherwise, remove the key-value (any value, not used). Finally, there are only two key-values ​​left in the dictionary. Output this Two keys.
Time complexity: O(n)
Space complexity: O(n)

Solution three (best)

Idea: Use grouped XOR. Since there is one more number than the previous question, after the first XOR one by one, you can only get the XOR values ​​of these two different numbers. Therefore, we still need to perform group XOR, divide two different numbers into two groups, and then XOR them one after another, it will be the same as the previous question.

Swift Code:

func findDifferentTwoNum(_ array: [Int]) -> [Int] {
    
    
    var res = Array<Int>()  //存放结果的数组
    var tmp = 0             //第一次数组逐个异或的结果,最终结果为:唯一两个不同数的异或值
    var rightMove = 0       //为了将两个不同数进行分组,找到tmp哪一位为1(异或值不同为1,说明这两个数在这一位不相同)
    var num1 = 0            //两个不同数其中一个
    var num2 = 0            //两个不同数另一个
    /**
     第一次数组逐个异或的结果
     最终结果tmp为:唯一两个不同数的异或值
     */
    for i in 0..<array.count{
    
    
        tmp = tmp ^ array[i]
    }
    /**
     tmp逐次右移
     找到tmp哪一位为1
     异或为1,说明那两个不同的数在该位上不相同,以此作为区分,将两个不同的数分到不同的组中去
     例如:rightMove:1 说明tmp右移一位,两个不同的数在第二位出现不同
     */
    while((tmp & 1) == 0){
    
    
        tmp = tmp >> 1
        rightMove += 1
    }
    /**
     ((array[i] >> rightMove) & 1)来进行分组,这两个不同的数结果一个为0,一个为1
     */
    for i in 0..<array.count{
    
    
        if(((array[i] >> rightMove) & 1) == 1){
    
    
            num1 = num1 ^ array[i]
        }else{
    
    
            num2 = num2 ^ array[i]
        }
    }
    /*
     最后分离出两个数
     */
    res.append(num1)
    res.append(num2)
    return res
}

Time complexity: O(n)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/weixin_44758107/article/details/127635990