If list A and list B are sorted in the same order (I will consider ascending, but the descent also works), this problem has a solution O (n). Below is some (informal and unverified) code. When the loop exits, indexMap should contain the indices of each element in list A, which correspond to the element in list B and the index of the associated element in list B.
int currentA;
int currentB;
int listAIndex = 0;
int listBIndex = 0;
Map <Integer, Integer> indexMap = new HashMap <Integer, Integer> ();
currentA = listA.get (listAIndex);
currentB = listB.get (listBIndex);
while ((listAIndex <listA.length) && (listBIndex <listB.length))
{
if (currentA == currentB)
{
indexMap.put (listAIndex, listBIndex);
++ listAIndex;
}
else if (currentA <currentB)
{
++ listAIndex;
}
else // if (currentA> currentB)
{
++ listBIndex;
}
}
source share