Requirement: Give an array of int, containing the number 0, 1, 2, ..., n, to find the missing number;
If the input is [0, 1, 2] returns 3
Input array nums = [0, 1, 2, 4]; should return 3
Input nums = [2, 0]; should return 1
Input nums = [1, 0]; should return 2
Method 1: First sort, then linear search
Elements are not necessarily arranged in order;
Sort the array first, and then search sequentially
Importjava.util.Arrays; Public classSolution { Public intMissingnumber (int[] nums) {Arrays.sort (nums); Sort Firstintindex; for(index = 0; index < nums.length; index + +)) { if(index!=Nums[index]) { returnindex; } } returnindex; }}
This method is relatively easy to think of, but the disadvantage is that the speed is too slow
Method 2: Xor method
There are no duplicate elements in the input array, which can be handled by different or unique features.
XOR: The difference is 1, the same is 0;
Any number that is different from or unchanged from 0, for example: A^0 = A;
Xor between multiple numbers, A^b^c = A^c^b = a^ (b^c)
1. Assume that the input array is [0, 1, 3] and should return 2
An array can be specified [0, 1, 2, 3], which contains the missing number X
The specified array is actually an array that satisfies the default criteria.
X does not exist, only occupies a position; places their elements in a bitwise XOR, i.e.
0, 1, x, 3
0, 1, 2, 3
0^1^2^3^0^1^3 = 0^0^1^1^3^3^2 = 0^2 = 2 Get result "2"
2. Assuming that the input array is [2, 0], use the array [0, 1, 2] to perform the following operations:
0^0^1^2^2 = 1 Get result "1"
3. Assuming that the input array is [0, 1, 2, 3], specify an array [0, 1, 2, 3] calculated using the method above
0^0^1^1^2^2^3^3 = 0 result error; should actually return 4
The array we use for the calculation can also be seen as the subscript for the input array, plus 1, which should be calculated using [0, 1, 2, 3, 4].
0, 1, 2, 3, X
0, 1, 2, 3, 4 results returned 4
Java code
Public int missingnumber (int[] nums) { ifnull | | nums.length = = 0) { return 0; } int result = 0; for (int i = 0; i < nums.length; i++) { ^= nums[i]; ^= i; } return result ^ nums.length;}
The code implements the XOR operation described previously
Missing number-find the missing digit