895. Maximum Frequency Stack 發表於 2023-02-13 | 分類於 leetcode problemsolution12345678910111213141516171819202122232425262728293031323334353637class FreqStack {private: unordered_map<int ,int> valToFreq; unordered_map<int ,stack<int>> freqToVals; int maxFreq ; public: FreqStack() { maxFreq = 0; } void push(int val) { int freq = valToFreq[val]; valToFreq[val]++; maxFreq = max(maxFreq, freq); freqToVals[freq].push(val); } int pop() { stack<int> &vals = freqToVals[maxFreq]; int ret = vals.top(); valToFreq[ret]--; vals.pop(); if(vals.empty()) maxFreq--; return ret; }};/** * Your FreqStack object will be instantiated and called as such: * FreqStack* obj = new FreqStack(); * obj->push(val); * int param_2 = obj->pop(); */