Remove Duplicates From Unsorted List

题目:

Write code to remove duplicates from an unsorted linked list.

Example

Given 1->3->2->1->4. Return 1->3->2->4

分析:

我用个hash table,做起来刚刚好!目前对hash的敏感程度已经略有提升。

解法:

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */

     ListNode *removeDuplicates(ListNode *head) {
        // Write your code here
        if (head == NULL || head->next == NULL) {
            return head;
        }

        ListNode dummy(0);
        dummy.next = head;

        unordered_set<int> hash;
        ListNode* prev = &dummy;
        ListNode* curr = head;

        while (curr != NULL) {
            if (hash.find(curr->val) != hash.end() ) {
                prev->next = curr->next;
                curr = prev->next;
            } else {
                hash.insert(curr->val);
                prev = prev->next;
                curr = curr->next;
            }
        }

        return dummy.next;
    }
};

results matching ""

    No results matching ""