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
- 2.1 Remove Dups
- 60. Permutation Sequence&字符串排列&8.7Permutations without Dups
- 2.1.11 Remove Element
- remove
- remove
- remove
- remove
- remove
- remove
- Remove
- Remove
- remove
- REMOVE
- Remove
- remove
- remove
- remove()
- Remove
- java hashCode()方法和equals()方法
- POJ 2778(DNA Sequence-Fail指针+矩阵快速幂)
- Leetcode Regular Expression Matching
- VS2015生成程序在别人电脑无法运行 msvcp140.dll 0x000007b 问题处理方法
- DZ论坛全自动挂机回帖助手2015.10.25实用版
- 2.1 Remove Dups
- BufferedFileCopy
- Android 里button.requestFocus()后,要点击两次才生效
- Http 与 Socket 区别
- 通信协议——HTTP、TCP、UDP
- 2.2 Return Kth to Last
- C/S和B/S两种架构的概念、区别和联系
- web服务器 原理
- 2.3 Delete Middle Node