82. Remove Duplicates from Sorted List II

  https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

  下面代码是自写hashmap版,练一下hashmap,用一般的map<int,int>红黑树map也能过。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 
10 
11 class MyHash {
12     static const int MAX = 123456;
13     static const int MOD = 123447;
14     static const int WHAT = 1237;
15     static const int INVALID = -1234478;
16     pair<int,int> a[MAX];
17     bool used[MAX];
18     int siz =0;
19     int myhash(int key){
20         if(siz==MOD)return MOD;
21         int pos = key*WHAT%MOD;
22         while(pos<0)pos=-(pos+1);
23         while(used[pos] && a[pos].first!=key)pos = (pos+1)%MOD;
24         return pos;
25     }
26 public:
27     int insert(pair<int,int> kv){
28         int pos = myhash(kv.first);
29         if(pos==MOD)return -1;
30         if(!used[pos]){
31             used[pos]=true;
32             siz++;
33         }
34         a[pos] = kv;
35         return 0;
36     }
37     int get(int key){
38         int pos = myhash(key);
39         if(a[pos].first==key)return a[pos].second;
40         else return INVALID;
41     }
42 
43     void add(int key, int ad){
44         int pos = myhash(key);
45         if(!used[pos]){
46             insert(make_pair(key,0));
47         }
48         a[pos].second+=ad;
49     }
50 };
51  
52 class Solution {
53 public:
54     ListNode* deleteDuplicates(ListNode* head) {
55         MyHash count;
56         ListNode* cur = head;
57         while(cur!=NULL){
58             count.add(cur->val,1);
59             cur=cur->next;
60         }
61         ListNode newhead(0);
62         newhead.next = head;
63         cur=&newhead;
64         while(cur!=NULL){
65             while(cur->next !=NULL && count.get(cur->next->val)>1){
66                 cur->next = cur->next->next;
67             }
68             cur = cur->next;
69         }
70         return newhead.next;
71     }
72 };
View Code

相关文章:

  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
  • 2021-10-08
  • 2021-12-07
  • 2021-08-08
  • 2021-09-10
猜你喜欢
  • 2021-07-24
  • 2022-01-21
  • 2021-10-22
  • 2021-05-25
  • 2021-09-20
  • 2021-09-18
相关资源
相似解决方案