digjim
BAN USERSince we only need to check the matrix on top-left, we can have two loop (i, j) , and i+j must less than the Nth.
array A is {1,3,4,8,10},
array B is {20, 22, 30, 40}.
the sum set will be{21(1+20),23(1+22 or 3+20), 25(3+22), 24(4+20), 26(4+22)...}
the 3rd element in the sum set is 24.
public static int GetNthSum(int[] arrayA, int[] arrayB, int nth)
{
// Remove duplicated first in two arrays
int[] sumList = new int[nth];
int tempSum;
int temp;
int tempCount = 0;
for (int i = 0; i < arrayA.Length && i < nth; i++)
{
for (int j = 0; j < arrayB.Length && j < nth && i + j <= nth; j++)
{
tempSum = arrayA[i] + arrayB[j];
for (int k = 0; k < nth; k++)
{
if (k == tempCount)
{
sumList[k] = tempSum;
tempCount++;
break;
}
else
{
if (tempSum == sumList[k])
{
break;
}
else if (tempSum < sumList[k])
{
temp = sumList[k];
sumList[k] = tempSum;
tempSum = temp;
}
}
}
}
}
if (tempCount == nth)
{
return sumList[tempCount - 1];
}
else
{
return -1;
}
}
- digjim November 14, 2013