How to find the missing number in integer array of a given range?

Check Out the example bellow:
[code lang=”java”]
public class MissingNumber {

public static void main(String args[]) {
System.out.println(Arrays.toString(getMissingNumber(new int[]{1, 2, 3, 9, 8, 11, 15, 14, 20}, 20)));

}

/**
*
* @param numbers
* @param count
* @return
* @see Simple Built in Class BitSet works fine to find out more than 1
* missing element.
*
*/
private static int[] getMissingNumber(int[] nums, int totalNumber) {

int missingCount = totalNumber – nums.length;
int[] missingArr = new int[missingCount];
BitSet bitSet = new BitSet(totalNumber);
for (int number : nums) {
bitSet.set(number – 1);
}
int missingIndex = 0;

for (int i = 0; i < missingCount; i++) {
missingIndex = bitSet.nextClearBit(missingIndex);
missingArr[i] = ++missingIndex;
}
return missingArr;
}

}
[/code]
Output:
[4, 5, 6, 7, 10, 12, 13, 16, 17, 18, 19]

Tagged on:     

Leave a Reply

X