原题链接:
https://leetcode.cn/problems/maximum-frequency-stack/description/
解法1: 双哈希
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
class FreqStack { HashMap<Integer,List<Integer>> map = new HashMap<>(); HashMap<Integer,Integer> cnts = new HashMap<>(); int max;
public FreqStack() { map = new HashMap<>(); cnts = new HashMap<>(); max = 0; } public void push(int val) { int freq = cnts.getOrDefault(val,0); freq++; cnts.put(val,freq); var arr = map.getOrDefault(freq,new ArrayList<>()); arr.add(val); map.put(freq,arr); max = Math.max(max,freq); } public int pop() { var arr = map.get(max); int ans = arr.remove(arr.size() - 1); cnts.put(ans,cnts.get(ans) - 1); if(arr.size() == 0){ max--; } return ans; } }
|