Java version using Set

  • 2
    public ListNode deleteDuplicates(ListNode head) {
        Set<Integer> s = new HashSet<Integer>();
        ListNode cur = head;
        ListNode pre = new ListNode(0); = head;
            if(s.contains(new Integer(cur.val))){
                s.add(new Integer(cur.val));
                pre =;
            cur =;
        return head;

  • 3

    Since the list is already sorted, the HashSet is not needed, you can just iterate through it, checking at each step either that the next one is different than the current one!

  • 0

    yeah, you are right.

Log in to reply

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