首页 > 解决方案 > 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;
}

标签: javahashmap

解决方案


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;
}

推荐阅读