Array of size \$(n-m)\$ with numbers from \$1..n\$ with \$m\$ of them missing. Find all of the missing numbers. The array is sorted.
Example: If
arr = [1,2,4,5,6,8]
, result should be3
&7
.
Here is my code which I would like to get reviewed:
import java.util.*;
class FindMissingNumsArray {
private List<Integer> missing = new ArrayList();
private void findMissingNums(int[] array) {
if(array == null)
return;
int length = array.length - 1;
if(length <= 1)
return;
getMissings(array, 0, length);
}
private void getMissings(int[] array, int lIndex, int hIndex) {
if(hIndex - lIndex == 2) {
fillMissings(array, lIndex, lIndex, hIndex);
return;
}
if(lIndex == hIndex)
return;
int i = lIndex;
int j = hIndex;
int mid = lIndex + (hIndex - lIndex) / 2;
getMissings(array, i, mid);
getMissings(array, mid + 1, j);
fillMissings(array, i, mid, j);
}
private void fillMissings(int[] array, int lIndex, int mid, int hIndex){
int i = lIndex;
int j = mid;
int k = hIndex;
int diff;
while(i < mid) {
diff = array[i + 1] - array[i];
for(int c = 1; diff > 1; diff--) {
if(!missing.contains(array[i] + c))
missing.add(array[i] + c);
c++;
}
i++;
}
while(j < k) {
diff = array[j + 1] - array[j];
for(int a = 1; diff > 1; diff--) {
if(!missing.contains(array[j] + a))
missing.add(array[j] + a);
a++;
}
j++;
}
}
private void printMissingList() {
for(int i: missing)
System.out.print(i + " ");
}
public static void main(String[] args) {
int[] array = {1, 4, 5, 6, 9, 10, 12, 15, 19};
int[] array1 = {0, 5, 6, 9, 10};
FindMissingNumsArray findMissings = new FindMissingNumsArray();
findMissings.findMissingNums(array);
System.out.print("Missing numbers in array are: ");
findMissings.printMissingList();
findMissings.missing = new ArrayList();
findMissings.findMissingNums(array1);
System.out.print("Missing numbers in array1 are: ");
findMissings.printMissingList();
}
}
I know there are ways to implement this better in terms of logic, run time, data structures, etc. It will be nice to know what I can do to improve the code.