简体   繁体   中英

Otimization removing elements from a list defined by another list in Java

My code is working, but the complexity is quadratic and I have been struggling to figure out how to improve it. I had to create a method to remove elements contained in a list from another list, the final test the list would be 50.000 elements long and the list of elements to remove would be 100 long.

This is the method I created:

public void remove(SingleLinkedList<T> toRemove){
       for(int j=0; j<toRemove.size; j++){
           Node<T> remC = toRemove.getN(j);
           if(toRemove.isEmpty()){
               break;
           }
           for(int i=0; i<size; i++){
               Node<T> prev = getN(i-1);
               Node<T> cur = getN(i);
               Node<T> next = getN(i+1);
               if(isEmpty()){
                   break;
               }
               if(remC.getValue().equals(cur.getValue())){
                   if(cur.getValue().equals(getFirst())){
                       removeFirst();
                       i--;
                   }else if(cur.getValue().equals(getLast())){
                       removeLast();
                       i--;
                   }else {
                       prev.setNext(next); //remove node cur
                       size--;
                       i--;
                   }
               }
           }
       }
   }

This is working but exceeds the time limit for the case with 50.000 elements list x 100 elements toRemove list, what I am trying to do there is at the first for loop I save the node with position j in the toRemove list and at the seccond for loop I check if the node of the main list with position i equals to it, and if so I remove it, otherwise I move to next node.

Any ideas?

I got this done, as Andreas suggested I got rid of the getN() 's, but that alone didn´t solve the issue so I made one loop outside the "i" for just to get rid of the first elements if they were inside the toRemove list (used .contains() for that), got rid of the "j" for , and then on my for loop I only had to deal with the elements inside the linked list, and the idea was that the curr node would be node 0 , acting as prev node , so I would aways search around cur.getNext() , since I made sure node 0 wasn't inside toRemove because of the first loop outside the for .

It worked fine without having to loop though the positions of the list every time, and even though this is not linear, at least is not quadratic so was good enough for the 50k list test.

:)

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