Huawei machine test - find out the different numbers in the array

It is known that all the numbers in the array are the same, only one is different, find the number

Three methods are provided here. The first two are easier to think of, and the third requires understanding of the XOR operation.

Solution 1 (high time complexity)

Idea: Two layers of for loops. If a number does not traverse to the same number as itself, return 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 is only one key-value left in the dictionary, and output the key. .
Time complexity: O(n)
Space complexity: O(n)

Solution three (best)

Idea: Use XOR operation. If the two values ​​​​a and b are not the same, the XOR result is 1. If the values ​​​​of a and b are the same, the XOR result is 0 (here a and b refer to 0 or 1). XOR has an important feature. The result of XORing a number with 0 is still that number . So based on the characteristics of XOR, we might as well analyze it. There is an array [1, 2, 3, 4, 3, 2, 1]. Traverse the array and XOR one by one. Since 1, 2, and 3 are the same, In the end, they are all 0. In the end, 0 is exclusive or 4 is equal to 4, and the result is easily obtained. (Advanced question in next article: Find two different numbers in an array)

Swift Code:

func findDifferentNum(_ array: [Int]) -> Int{
    
    
	var res = 0
	for i in 0..<array.count{
    
    
		res = res ^ array[i]
	}
	return res
}

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

Guess you like

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