Here is what i did. What can i do further? Can anybody suggest? I am looking for bitset solution.
public static void main(String args[]) {
// one missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
// two missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
// three missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
// four missing number
printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
// Only one missing number in array
int[] iArray = new int[]{1, 2, 3, 5};
int missing = getMissingNumber(iArray, 5);
System.out.printf("Missing number in array %s is %d %n",
Arrays.toString(iArray), missing);
}
asked Mar 13, 2015 at 16:03
-
1Where's your implementation?Ravi K Thapliyal– Ravi K Thapliyal2015年03月13日 16:05:14 +00:00Commented Mar 13, 2015 at 16:05
2 Answers 2
For n sequential numbers, the sum s = n(n+1)/2.
Sum up the numbers in the array and subtract it from s to find the missing number.
-
Plus one, exactly my answer and earlier.Bathsheba– Bathsheba2015年03月13日 16:08:09 +00:00Commented Mar 13, 2015 at 16:08
If n
is the largest number, and there is only one missing, then the missing number is
n * (n + 1) / 2 - sum{elements in your array}
The first term is the sum of n
consecutive integers from 1 to, and including, n
.
answered Mar 13, 2015 at 16:06
-
He was asking about the bitset solutionControlAltDel– ControlAltDel2015年03月13日 16:07:37 +00:00Commented Mar 13, 2015 at 16:07
-
Which is a terrible idea.Bathsheba– Bathsheba2015年03月13日 16:07:52 +00:00Commented Mar 13, 2015 at 16:07
-
terrible is a little strong :)ControlAltDel– ControlAltDel2015年03月13日 16:12:26 +00:00Commented Mar 13, 2015 at 16:12
-
Yes, you have a point. There does exist an O(log N) solution, whereas mine is O(N) due to the array sum. So my answer is not as impeccable as I originally thought.Bathsheba– Bathsheba2015年03月13日 16:14:48 +00:00Commented Mar 13, 2015 at 16:14
lang-java