Can Java use HashMap to store iterator to solve this problem?


  • 0
    S

    I looked up the answers of this question. Some used hash map to store the iterator and said it took O(1) in C++. I try to solve it in Java by this solution, which may use ListIterator. However, the remove() of the ListIterator calls the remove() of the List, which may still take O(n) to delete the node.

    	if(mp.containsKey(key)){
    		ListIterator it = mp.get(key);
    		it.next();
    		li.remove();
    	}
    

    remove() of ListIterator

       public void remove() {  
                    checkForComodification();  
                    Entry<E> lastNext = lastReturned.next;  
                    try {  
                        **LinkedList.this.remove(lastReturned);**  
                    } catch (NoSuchElementException e) {  
                        throw new IllegalStateException();  
                    }  
                if (next==lastReturned)  
                        next = lastNext;  
                    else  
                nextIndex--;  
                lastReturned = header;  
                expectedModCount++;  
            }  
    

    I want to know if I understand this solution correct or there's difference between C++ and Java at this point.

    Thanks


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.