简体   繁体   中英

compare list with minimal time complexity in java

I have two list

List<MyData> listA = new ArrayList<MyData>() and List<MyData> listB = new ArrayList<MyData>() both contain object of type MyData and MyData contain these variables.

Class MyData {
    String name;
    boolean val
}

I got to write a program to compare two arraylist are equal or not with less time complexety.I am not overiding equals and hashcode in Mydata class as it an already existing class and modification may effect on different behaviour on application. Code i wrote is

forEach(MyData a:listA ){

    forEach(MyData b:listB ){
        if(a.getName.equals(b.getName)){
        }

    }
}

First of all forEach is not valid Java syntax. It should be for .

Second of all, you don't want to have a nested loop, since that would give you O(n^2) time complexity.

You should have one loop that iterates over both lists :

if (listA.size() != listB.size())
    return false;
for (int i = 0; i < listA.size(); i++){
    MyData a = listA.get(i);
    MyData b = listB.get(i);
    if (!a.getName.equals(b.getName))
        return false;
}
return true;

That would give you O(n) time complexity.

A double foreach loop will give you a complexity in O(n^2) ... That's not optimal.

Are your lists sorted? if so you could do a comparison one by one (that's a complexity O(n) ) If not, sort them! The best generic sorting algorithms have a complexity of O(n.log(n)) . So overall you will have the same complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM