Hello all,
I am trying to solve this question and I've pasted my solution below. I want to know points to improve in my pasted code, so that it becomes more efficient.
Implement a function that takes in 2 arrays/list of integers, and return the common numbers.
e.g A: [2,3, 2, 4, 5] B: [9, 2, 2, 2, 3, 3]
Return in any order: [2, 2, 3]
- The following function takes in arrays A and B with sizes num1 and num2 resp.
- It also takes array C to store duplicate values, with size k (lesser of num1 and num2)
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
|
int insertAndCheck(int* A, int* B, int* C, int num1, int num2, int k)
{
if(!A || !B)
{
cout << "Array A or B are null" << endl;
return NULL; //NULL indicates error message;
}
if(!C)
{
cout << "Array to store duplicate values is passed as NULL" << endl;
return NULL;
}
if(num1 = 0 || num2 = 0)
{
cout << "Number of elements in A or B or both are zero. Nothing to check." << endl;
return NULL;
}
for(int i = 0; i < num1; i++)
{
int x = HashTable1.getValue(A[i]);
++x;
HashTable1.insert(A[i], x);
}
int size = k;
k = 0;
for(int j = 0; j < num2; j++)
{
int y = HashTable1.getValue(B[j]);
if(y != 0)
{
--y; //decrement the value at the index, each time the value is duplicated
C[k++] = B[j];
if(k > size)
{
cout << "Size of array C incorrect" << endl;
return NULL;
}
HashTable1.insert(B[j], y);
}
else
{
cout << "Element did not exist previously and hence not duplicated" << endl;
}
}
return (k-1); //returns number of duplicated elements in array C
}
|
Please let me know:
- If I could use vectors instead of arrays.
- Where could I use exceptions?