250ms JAVA solution, use two hashset and a fakeHeader, it is not the best solution ,but easy to come up with


  • 0
    S
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            Set<Integer> set1 = new HashSet<Integer>();
            Set<Integer> set2 = new HashSet<Integer>();
            ListNode fakeHeader = new ListNode(0);
            fakeHeader.next = head;
            ListNode ptr = fakeHeader;
            while(ptr.next != null) {
                if(set1.add(ptr.next.val)) {
                    ptr = ptr.next;
                } else {
                    set2.add(ptr.next.val);
                    ptr.next = ptr.next.next;
                }
            }
            ptr = fakeHeader;
            while(ptr.next != null) {
                if(set2.contains(ptr.next.val)) {
                    ptr.next = ptr.next.next;
                } else {
                    ptr = ptr.next;
                }
            }
            return fakeHeader.next;
        }
    }

  • 0
    S

    i am sorry for not noticing this is a sorted array. So the method may be more easier use two pointers to traverse. But mine method can still use for unsorted array.


Log in to reply
 

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