Problem Description
Choose n numbers from the n+1 numbers of 0,1,2,...,n to form an ordered array, find the missing number among these n numbers, and require O(n) to be as small as possible.
Input description:
Input an array (0-n)
Output description:
output missing numbers
Example
Example 1
Enter
[0,1,2,3,4,5,7]
Output
6
Solutions
analysis
- Through loop
- Through mathematical thinking, the sum of 1-n is n*(n+1)/2
- Through the characteristic of XOR, the calculated result is
the XOR of the same number as 0, and the XOR of any number with 0 is the original value.
method
- Through the loop, determine whether the difference between before and after is greater than 1
- Through mathematical thinking, the sum of 1-n is n*(n+1)/2, subtract all the numbers in turn, and the result is the missing number
- Through the characteristic of XOR, suppose array 0,1,3,4
temp = 4^(0^0)^(1^1)^(2^3)^(3^4)
=(4^4)^(0^0)^(1^1)^(3^3)^2
=0^0^0^0^2
=2
Code
// 思路1
public class Solution {
public int solve(int[] a) {
if (a == null || a.length == 0) {
return -1;
}
for (int i = 1; i < a.length; i++) {
if (a[i] - a[i - 1] > 1) {
return a[i] - 1;
}
}
return -1;
}
}
public class Solution {
// 通过数学的方法
public int solveByMath(int[] a) {
if (a == null || a.length == 0) {
return -1;
}
int n = a[a.length - 1];
int sum = n * (n + 1) / 2;
for (int i = 0; i < a.length; i++) {
sum -= a[i];
}
return sum;
}
}
public class Solution {
// 通过位运算
public int solveByBitOperation(int[] a) {
if (a == null || a.length == 0) {
return -1;
}
int temp = a.length;
for (int i = 0; i < a.length; i++) {
temp ^= a[i] ^ i;
}
return temp;
}
}
If you want to test, you can go directly to the link of Niuke.com to do the test