全 O(1) 的数据结构

107 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

题目描述

  • 请你设计一个用于存储字符串计数的数据结构,并能够返回计数最小和最大的字符串。

  • 实现 AllOne 类:

  1. AllOne() 初始化数据结构的对象。
  2. inc(String key) 字符串 key 的计数增加 1 。如果数据结构中尚不存在 key ,那么插入计数为 1 的 key 。
  3. dec(String key) 字符串 key 的计数减少 1 。如果 key 的计数在减少后为 0 ,那么需要将这个 key 从数据结构中删除。测试用例保证:在减少计数前,key 存在于数据结构中。
  4. getMaxKey() 返回任意一个计数最大的字符串。如果没有元素存在,返回一个空字符串 "" 。
  5. getMinKey() 返回任意一个计数最小的字符串。如果没有元素存在,返回一个空字符串 "" 。
  • 示例
输入
["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"]
[[], ["hello"], ["hello"], [], [], ["leet"], [], []]
输出
[null, null, null, "hello", "hello", null, "hello", "leet"]

解释
AllOne allOne = new AllOne();
allOne.inc("hello");
allOne.inc("hello");
allOne.getMaxKey(); // 返回 "hello"
allOne.getMinKey(); // 返回 "hello"
allOne.inc("leet");
allOne.getMaxKey(); // 返回 "hello"
allOne.getMinKey(); // 返回 "leet"

思路分析

  • 根据题目意思,我们需要返回数量最多和数量最少的字符,所以肯定要对字符进行统计处理。
  • 每当添加或删除某个单词动作完成之后,我们都要调整数据结构中的数据位置,以便于随时查询最大、最小数量字符。
  • 由以上我们知道可以用 HashMap/HashSetHashMap / HashSet 来统计字符数量。那么如何维护字符按数量的多少保持有序性呢?PriorityQueuePriorityQueue oror Collections.sort(List)Collections.sort(List) oror TreeMapTreeMap 。或者其他数据结构。但是题目对时间复杂度有要求,所以我们尽量避免线性排序处理模式。
  • 本题我用 TreeMapTreeMap 来维护字符数量的顺序问题,也是时间复杂度比较接近 O(1)O(1) 的一种方法。因为用到树的排序,所以每一次处理数据的平均时间复杂度是 O(log)O(log) 级别的。

AC 代码

class AllOne {

    public AllOne() {}
    // 统计字符数量.
    Map<String,Integer> keyWithCount = new HashMap<>();
    // 维护字符按照数量进行排序,相同数量的字符可能有多个. 默认为升序.
    TreeMap<Integer,Set<String>> countWithKey = new TreeMap<>();

    public void inc(String key) {
        if (!keyWithCount.containsKey(key)) {
            // 原来不存在该字符的话,直接加入即可.
            keyWithCount.put(key,1);
            if (!countWithKey.containsKey(1)) countWithKey.put(1,new HashSet<>());
            countWithKey.get(1).add(key);
        } else {
            // 原来已经存在该字符的话,应该更新字符对应的数量.
            int count = keyWithCount.get(key) + 1;
            countWithKey.get(count - 1).remove(key);
            if (countWithKey.get(count - 1).isEmpty()) {
                countWithKey.remove(count - 1);
            }

            keyWithCount.put(key,count);
            if (!countWithKey.containsKey(count)) countWithKey.put(count,new HashSet<>());
            countWithKey.get(count).add(key);
        }
    }
    
    public void dec(String key) {
        // 该方法与添加方法思路一致,可参考上一个注解.
        int count = keyWithCount.get(key);
        if (count == 1) {
            keyWithCount.remove(key);
            countWithKey.get(1).remove(key);
        } else {
            keyWithCount.put(key,count - 1);
            countWithKey.get(count).remove(key);
            if (!countWithKey.containsKey(count - 1)) countWithKey.put(count - 1,new HashSet<>());
            countWithKey.get(count - 1).add(key);
        } 
        if (countWithKey.get(count).isEmpty()) {
            countWithKey.remove(count);
        }
    }
    
    public String getMaxKey() {
        if (keyWithCount.isEmpty()) return "";
        // 取出一个数量最多的字符.
        String max = countWithKey.lastEntry().getValue().iterator().next();
        return max;
    }
    
    public String getMinKey() {
        if (keyWithCount.isEmpty()) return "";
        // 取出一个数量最少的字符.
        String min = countWithKey.firstEntry().getValue().iterator().next();
        return min;
    }
}

总结

  • 每次遇到 hard 都会收获满满的!本题属于设计类型题目,我们觉得是在考察我们对数据结构的熟悉与数据结构设计能力。双向链表版本的抽时间写写呃呃!