1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <iostream>
using namespace std;
int* findMissing(int arr[], int n, int& resArrSize);
void printArray(int arr[], int arrSize);
int main() {
//array 1 test
int array1[] = {3, 1, 3, 0, 6, 4};
int array1Size = 6;
int array1resArrSize = 0;
int* missingArray1;
missingArray1 = findMissing(array1, array1Size, array1resArrSize);
cout<<"Array 1 test"<<endl;
cout<<"before: ";
printArray(array1, array1Size);
cout<<endl<<"After: ";
printArray(missingArray1, array1resArrSize);
cout<<"\n";
//when place here the output varies between [1,5,6] and [1,5]
//delete[] missingArray1;
//array 2 test
int array2[] = {0,2,3,4,0,0};
int array2Size = 6;
int array2resArrSize = 0;
int* missingArray2;
missingArray2 = findMissing(array2, array2Size, array2resArrSize);
cout<<"Array 1 test"<<endl;
cout<<"before: ";
printArray(array2, array2Size);
cout<<endl<<"After: ";
printArray(missingArray2, array2resArrSize);
//cleanup
//when missingArray1 is placed here, it is consistently [1,5,6]
delete[] missingArray1;
delete[] missingArray2;
return 0;
}
int* findMissing(int arr[], int n, int& resArrSize){
int* numCount = new int[n];
int* missNums = new int[n];
//fill array with zeros
for(int i = 0; i<n;i++){
numCount[i] = 0;
}
for(int i = 0; i < n; i++){
int index = 0;
index = arr[i];
(numCount[index])++;
}
int missNumsindex = 0;
for(int i = 0; i <= n; i++){
if(numCount[i] == 0){
missNums[missNumsindex] = i;
missNumsindex++;;
}
resArrSize = missNumsindex;
}
return missNums;
}
void printArray(int arr[], int arrSize){
cout<<"[ ";
for(int i = 0; i < arrSize; i++){
if(i == arrSize - 1){
cout<<arr[i];
}else {
cout << arr[i] << ", ";
}
}
cout<<" ]";
}
|