/**
* Your FreqStack object will be instantiated and called as such:
* FreqStack obj = new FreqStack();
* obj.push(x);
* int param_2 = obj.pop();
*/
import java.util.ArrayList;
import java.util.*;
import java.util.HashMap;
public class FreqStack {
private ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
private HashMap<Integer, Integer> integerHashMap = new HashMap<Integer, Integer>();
private List<Integer> frequencyNumberList = new ArrayList<Integer>();
private int MAX_Count = 0;
public FreqStack() {
}
public void push(int x) {
integerArrayList.add(x);
updateNumberFrequency(integerHashMap, x);
//if(frequencyNumberList.contains(x)){
// frequencyNumberList.clear();
// frequencyNumberList.add(x);
//}else {
// frequencyNumberList.clear();
//}
}
public int pop() {
//if(frequencyNumberList.isEmpty()){
// frequencyNumberList = getFrequencyNumber(integerHashMap);
//}
int removeIndex = -1;
int popResult = 0;
int count = 0;
for(int i = integerArrayList.size() - 1; i >= 0; i--){
if(integerHashMap.get(integerArrayList.get(i)) == MAX_Count){
removeIndex = i;
popResult = integerArrayList.get(i);
integerHashMap.put(integerArrayList.get(i), MAX_Count-1);
MAX_Count = findMaxCount(integerHashMap);
break;
}
//if(frequencyNumberList.contains(integerArrayList.get(i))){
// removeIndex = i;
// popResult = integerArrayList.get(i);
// count = integerHashMap.get(integerArrayList.get(i));
// integerHashMap.put(integerArrayList.get(i), count-1);
// break;
//}
}
integerArrayList.remove(removeIndex);
//frequencyNumberList.remove((Integer)popResult);
return popResult;
}
public void updateNumberFrequency(Map<Integer, Integer> numberFrequency, int x){
if(numberFrequency.keySet().contains(x))
{
Integer temp = numberFrequency.get(x);
temp++;
MAX_Count = temp > MAX_Count ? temp : MAX_Count;
numberFrequency.put(x,temp);
}else {
numberFrequency.put(x,1);
MAX_Count = 1 > MAX_Count ? 1 : MAX_Count;
}
}
public int findMaxCount(Map<Integer, Integer> numberFrequency){
int max = 0;
for (Integer freq:numberFrequency.values()) {
max = freq > max ? freq : max;
if(max == MAX_Count){
return MAX_Count;
}
}
return max;
}
public List<Integer> getFrequencyNumber(Map<Integer, Integer> numberFrequency){
List<Integer> result = new ArrayList<Integer>();
int maxCount = 0;
for (Map.Entry<Integer,Integer> entry : numberFrequency.entrySet()) {
if(entry.getValue() > maxCount){
result.clear();
maxCount = entry.getValue();
result.add(entry.getKey());
}else if(entry.getValue() == maxCount){
result.add(entry.getKey());
}else {
continue;
}
}
return result;
}
}