There are few solutions:
1. Add from 1 to N, and minus each element from the array, the remaining is the result;
2. Improved from solution 1, as the sum could be too large. Use the XOR for from 0 to N, and then XOR each element in the array, the remaining is the result.
3. But solution 1 and 2 are not good for duplicates, so another solution is proposed,as an array size of the biggest element in the array, loop the array then find the one(s) appear zero times.
4. Improved from solution 3, as the integer array takes O(n) space, and bit is enough for this problem. Use integer which is 32 bits instead of array which could save 31 times space. 1 means appearance, and 0 otherwise.
public class FindMissingK {
public static void main(String[] args) {
int[] input = { 3, 1, 2, 4, 0 };
System.out.println(findMissKValue(input, 5));
}
private static int findMissKValue(int[] inputs, int n) {
int process = 0;
for (int i = 1; i <= n; i++) {
process = process ^ i;
}
for (int i = 0; i < inputs.length; i++) {
// if (inputs[i] != 0) {
process = process ^ inputs[i];
// }
}
return process;
}
}
没有评论:
发表评论