Leetcode-895 Maximum Frequency Stack(最大频率堆栈)

 1 class FreqStack
 2 {
 3     public:
 4         unordered_map<int,int> hash;
 5         vector<int> stk;
 6         int max_times;
 7         int times_table[10001];
 8         FreqStack()
 9         {
10             memset(times_table,0,sizeof(times_table));
11             max_times = 0;
12         }
13 
14         void push(int x)
15         {
16             stk.push_back(x);
17 
18             auto ptr_to_hash = hash.find(x);
19             if(ptr_to_hash==hash.end())
20             {
21                 hash.insert(make_pair(x,1));
22                 times_table[1] ++;
23                 max_times = max(1,max_times);
24             }
25             else
26             {
27                 times_table[ptr_to_hash->second] --;
28                 ptr_to_hash->second += 1;
29                 times_table[ptr_to_hash->second] ++;
30                 max_times = max(ptr_to_hash->second,max_times);
31             //    cout << x << " " << max_times << endl;
32             }
33         }
34 
35         int pop()
36         {
37             for(int i = stk.size()-1;i >= 0;i --)
38             {
39                 auto ptr_to_hash = hash.find(stk[i]);
40                 if(ptr_to_hash->second==max_times)
41                 {
42                     int result = stk[i];
43                     stk.erase(stk.begin()+i);
44                     times_table[ptr_to_hash->second] --;
45                     ptr_to_hash->second -= 1;
46                     times_table[ptr_to_hash->second] ++;
47                     if(!times_table[max_times])
48                     {
49                         max_times --;
50                     }
51                     return result;
52                 }
53             }
54             return max_times;
55         }
56 };

 

posted @ 2018-08-26 14:35  Asurudo  阅读(518)  评论(0编辑  收藏  举报