2.1 Remove Dups

来源:互联网 发布:未注册双拼域名 编辑:程序博客网 时间:2024/06/11 08:22

For single linked list problem I use LeetCode struct for them:

    struct ListNode{        int val;        ListNode* next;        ListNode(int x): val(x), next(NULL)){}    };

And for testing, using following three functions:

    void insert( ListNode * & head, int data ){        ListNode * newNode = new ListNode(data);        newNode->next = head;        head = newNode;    }    void printList( ListNode * head ) {        while( head ) {            cout << head->val << "-->";            head = head->next;        }        cout << "NULL" << std::endl;    }    //generate a random int between min and max    static inline int random_range(const int min, const int max) {        random_device rd;        mt19937 mt(rd());        uniform_int_distribution<int> distribution(min, max);        return distribution(mt);    }    int main(int argc, const char * argv[]) {        // insert code here...        std::cout << "Method 1 : \n";        ListNode * head = nullptr;        for ( int i = 0; i < 10; ++i ) {            insert(head, random_range(1,7));        }        printList(head);        removeDup(head);        printList(head);        std::cout << "Method 2 : \n";        ListNode * head1 = nullptr;        for ( int i = 0; i < 10; ++i ) {            insert(head1, random_range(1,7));        }        printList(head1);        removeDup2(head1);        printList(head1);        return 0;    }

For this problem, there is a trade off between time and space.
The first solution is O(n) time w/ O(n) space whereas second has O(n^2) time w/ O(1) space.

Note: in case of memory leaking, in C++ we have to deallocate memory by ourself QWQ.

    void removeDup(ListNode* head){        if(!head || !head->next) return;        unordered_map<int, int> mp;        ListNode* pre = head;        ListNode* cur = head->next;        mp[head->val] = 1;        while (cur) {            while (cur && mp.find(cur->val) != mp.end()) {                ListNode* tmp = cur;                cur = cur->next;                delete tmp;            }            pre->next = cur;            pre = cur;            if (cur) {                mp[cur->val] = 1;                cur = cur->next;            }        }    }
    void removeDup2 (ListNode* head){        ListNode* cur = head;        ListNode* run = nullptr;        while (cur){            run = cur;            while (run->next){                if (run->next->val != cur->val) run = run->next;                else{                    ListNode* tmp = run->next;                    run->next = tmp->next;                    delete tmp;                }            }            cur = cur->next;        }    }
0 0