Reputation: 9
public static int Count( List<Integer> lst1, List<Integer> lst2)
{
Iterator<Integer> itr1 = lst1.iterator();
int count=0;
while ( itr1.hasNext() )
{
Integer x = itr1.next();
Iterator<Integer> itr2 = lst2.iterator();
while ( itr2.hasNext() )
if ( x.equals( itr2.next()) )
count++;
}
return count;
}
I go for both because for the fist while loop O(n)
then the secong while O(n)
and the if also O(n) = O(n^3)
. I dont know if I am wrong or not?
Upvotes: 0
Views: 391
Reputation: 14699
It's O(size(lst1)*size(lst2))
. For all xi in lst1
, you compare xi to every element in lst2
. In this case, it's more accurately Θ(size(lst1)*size(lst2))
, since it's bounded both above and below by size(lst1)*size(lst2)
.
Upvotes: 6
Reputation: 121998
No doubt.. @steven gave a nice mathematical rep. The big O happening here is the multiplication of the sizes of lists providing to the method.
Because with each element in the list1
is comparing with each element in the list2
..So that the loop runs for SizeofList1*SizeOfLit2
.
Here is beginner guide with loops.Hope you will get it.
Upvotes: 0