java - HackerRank 频率查询(Java)
问题描述
这是 HackerRanks 频率查询问题,我不知道为什么它会失败 4 个测试用例,特别是用例 8、9、11 和 12。我在下面提供了我的代码以及我的逻辑注释。如果有人可以解释我的逻辑中的缺陷以通过所有测试用例,将不胜感激。
这是问题 频率查询问题的链接
static List<Integer> freqQuery(List<List<Integer>> queries) {
//key stores the inserted data value
//value stores the occurence/count of each value
HashMap <Integer,Integer> hm = new HashMap();
ArrayList<Integer> answer = new ArrayList<Integer>();
for(int i = 0; i < queries.size(); i++){
//[(1,1),(2,2),(3,2),(1,1)]
//rule is idx 0 in each array, value/key is idx 1 in each array
int key = queries.get(i).get(1);
int rule = queries.get(i).get(0);
//rule add to hashmap
if(rule == 1){
//[1,x], stores x into the hashmap if exists and increments frequency
if(hm.containsKey(key)){
hm.put(key, hm.get(key) + 1);
}
//otherwise add to hashmap with frequency of 1
else{
hm.put(key, 1 );
}
}
else if(rule == 2){
//[2,y], remove y from hashmap if exists
if(hm.containsKey(key)){
hm.put(key, hm.get(key) - 1);
}
}
else{
//[3,z], if z in hashmap add 1 to answer arraylist
//if hm contains, add 1 to arraylist
if(hm.containsValue(key)){
answer.add(1);
}
else{
answer.add(0);
}
}
}
return answer;
}
解决方案
static List<Integer> freqQuery(List<List<Integer>> queries) {
HashMap<Integer, Integer> frequencies = new HashMap<>();
int[] quantities = new int[queries.size() + 1];
List<Integer> result = new ArrayList<>();
int frequency, value;
for (List<Integer> query : queries) {
value = query.get(1);
switch (query.get(0)) {
case 1:
frequency = frequencies.getOrDefault(value, 0);
frequencies.put(value, frequency + 1);
quantities[frequency]--;
quantities[frequency + 1]++;
break;
case 2:
frequency = frequencies.getOrDefault(value, 0);
if (frequency == 0)
break;
if (frequency == 1)
frequencies.remove(value);
else
frequencies.put(value, frequency - 1);
// process qt
quantities[frequency]--;
quantities[frequency - 1]++;
break;
case 3:
if (value >= quantities.length)
result.add(0);
else
result.add(quantities[value] > 0 ? 1 : 0);
break;
}
}
return result;
}
推荐阅读
- python - 折线图上的峰值检测
- python - 动态重命名python嵌套字典中的键
- pandas - 来自一个输入请求的多个输入
- python - 按列分组,然后在 pandas 中的组内执行特定操作
- excel - 为什么单击 ActiveX 按钮时出现运行时错误 1004
- r - 如何使用相同的标签将两个季节的信息组合在一个箱线图中?
- javascript - 如何使用 jquery 制作动态自定义文本区域?
- r - 在 2 行上使用带有变量的 melt 或 pivot_longer
- python - Python 电子邮件垃圾邮件发送者仅发送到一封电子邮件
- java - 将单独的日期、小时、分钟、秒和 AM/PM 转换为 java.time.Instant