0

I have several lists of varying size, each index of the list contains both a key and an object : list1.add('Key', obj).

The lists are all sorted.

My aim is to iterate through the list and match 1 or more items in list 2,3,4 or n to an item in the mainList using the key.

Currently I do something along the lines of:

for i to list1 size
   for j to list2 size
   if list1[i] = list2[j]
      do stuff 

As I loop through I'm, using boolean values to exit quickly using a if current != previous check and I'm deleting the object from the list I take it from.

it's working fine but I now have another list that I need to match and possible another n lists afterwards. The lists are of different sizes.

the 2 options that I can see are to either repeat the above segment of code several times where the inner list is changed - I do no like this approach.

The other option is to extend the above and once one inner loop is finished, move onto the next:

  for i to list1 size
       for j to list2 size
       if list1[i] = list2[j]
          do stuff 
       for k to list2 size
       if list1[i] = list2[k]
          do stuff 

I'd like to think I'm correct in thinking that the 2nd is more efficient however I'm unsure. Also, is there a better way?

Thanks for any advice / help.

Edit: Barmar in SO has stated that they are the same time complexity but it might be considered off-topic so I've added here in case it'll help someone else and in case there is a better solution.

Raphael
  • 72,336
  • 29
  • 179
  • 389
null
  • 101
  • 2

0 Answers0