Java version using Set


  • 2
    V
    public ListNode deleteDuplicates(ListNode head) {
        Set<Integer> s = new HashSet<Integer>();
        ListNode cur = head;
        ListNode pre = new ListNode(0);
        pre.next = head;
        while(cur!=null){
            if(s.contains(new Integer(cur.val))){
                pre.next = cur.next;
            }else{
                s.add(new Integer(cur.val));
                pre = pre.next;
            }
            cur = cur.next;
        }
        return head;
    }

  • 3
    M

    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
    V

    yeah, you are right.


Log in to reply
 

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