Saturday, August 10, 2013

Coding Exercises Day 8a (Problem #9)

Problem:
Write code to remove duplicates from an unsorted linked list.

 void removeDuplicates(List list) {
  Set previousElements = new HashSet();
  
  Iterator iter = list.iterator();

  while (iter.hasNext()) {
    T current = iter.next();
    
    if (previousElements.contains(current)) {
      iter.remove();
    }
    else {
      previousElements.add(current);
    }
  } 
}
Followup:
How would you solve this problem if a temporary buffer is not allowed?
 void removeDuplicates(List list) {
  // Sort the list first.
  Collections.sort(list);

  T previous = null;'

  Iterator iter = list.iterator();
  
  while(iter.hasNext()) {
    T current = iter.next();
    
    if (null == previous) {
      previous = current;
    }
    else if (previous == current) {
      iter.remove();
    }
    else {
      previous = current;
    }
  }
}

No comments:

Post a Comment