I have written an O(N^^2) running time function which does not use hashtables but handles negative numbers and duplicate numbers apparently OK. I handle negative numbers in an integer array by adding an large postive number(e.g. 100) to all the integers in the array. Then, I adjust the target by target += (4 * 100)
. Then when I find a result, I subtract out the 100 from the integers in the result. Here is my code and test cases: Please let me know if this o(N^^2) time complexity.
struct maryclaranicholascameron{
int sum;
int component1;
int component2;
};
void Another2PrintSum(int arr[], int arraysize, int target){
int i(arraysize -1);
int j(arraysize -2);
int temp(target);
int temp2(0);
int m(0);
int n(0);
int sum(0);
int original_target(target);
for (int ctr = 0; ctr < arraysize; ctr++){
sum += arr[ctr];
}
for (int ctrn = 0; ctrn < arraysize; ctrn++){
arr[ctrn] += 100;
}
maryclaranicholascameron* temparray = new maryclaranicholascameron[sum + (arraysize *100)];
memset(temparray, 0, sizeof(maryclaranicholascameron) * (sum + 400));
for (m = 0; m < arraysize; m++){
for (n = m + 1; n < arraysize; n++){
temparray[arr[m] + arr[n]].sum = arr[m]+ arr[n];
temparray[arr[m] + arr[n]].component1 = m;
temparray[arr[m] + arr[n]].component2 = n;
}
}
target += (4 * 100);
original_target = target;
bool found(false);
while (i >= 0 && i < arraysize && found == false){
target -= (arr[i]);
while(j >= 0 && j < arraysize && found == false){
temp2 = target;
target -= (arr[j]);
if (i != j && temparray[target].sum == target &&
temparray[target].sum != 0 &&
temparray[target].component1 != i &&
temparray[target].component2 != i &&
temparray[target].component1 != j &&
temparray[target].component2 != j){
printf("found the 4 integers i = %d j = %d m = %d n = %d component1 = %d component = %d i %d j %d\n",
arr[i] - 100,
arr[j] - 100,
arr[temparray[target].component1] - 100,
arr[temparray[target].component2] - 100,
temparray[target].component1,
temparray[target].component2,
i,
j);
found = true;
break;
}
j -= 1;
target = temp2;
}
i -= 1;
j = i;
target = original_target;
}
if (found == false){
printf("cannot found the 4 integers\n");
}
delete [] temparray;
}
// test cases
int maryclaranicholas[] = {-14,-14,-14,-14,-12 ,-12, -12 ,-12 ,-11, -9,-8,-7,40};
Another2PrintSum(maryclaranicholas, 13,-2};
int testarray[] = {1,3,4,5,7,10};
Another2PrintSum(testarray, 6, 20);