Remove duplicates from an unsorted linked list

前端 未结 19 1094
梦如初夏
梦如初夏 2020-12-09 06:54
import java.util.*;
/*
 *  Remove duplicates from an unsorted linked list
 */
public class LinkedListNode {  
    public int data;  
    public LinkedListNode next;          


        
19条回答
  •  無奈伤痛
    2020-12-09 07:26

    All the solutions given above looks optimised but most of them defines custom Node as a part of solution. Here is a simple and practical solution using Java's LinkedList and HashSet which does not confine to use the preexisting libraries and methods.

    Time Complexity : O(n)

    Space Complexity: O(n)

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static LinkedList removeDupsUsingHashSet(LinkedList list) {
    
        HashSet set = new HashSet<>();
        for (int i = 0; i < list.size();) {
            if (set.contains(list.get(i))) {
                list.remove(i);
                continue;
            } else {
                set.add(list.get(i));
                i++;
            }
        }
        return list;
    }
    

    This also preserves the list order.

提交回复
热议问题