leetcode 全 O(1) 的数据结构 java

题干

实现一个数据结构支持以下操作:

Inc(key) - 插入一个新的值为 1 的 key。或者使一个存在的 key 增加一,保证 key 不为空字符串。
Dec(key) - 如果这个 key 的值是 1,那么把他从数据结构中移除掉。否者使一个存在的 key 值减一。如果这个 key 不存在,这个函数不做任何事情。key 保证不为空字符串。
GetMaxKey() - 返回 key 中值最大的任意一个。如果没有元素存在,返回一个空字符串""。
GetMinKey() - 返回 key 中值最小的任意一个。如果没有元素存在,返回一个空字符串""。
挑战:以 O(1) 的时间复杂度实现所有操作

想法

hashmap存储
使用到了hashmap的keyset功能
网上有非常多的用hashmap+双链表
不再赘述
代码可以参考
这个写的很好

Java代码

package bytedance.data;

import java.util.HashMap;


class AllOne {

    HashMap<String, Integer> map;

    /**
     * Initialize your data structure here.
     */
    public AllOne() {
        map = new HashMap<>();

    }

    /**
     * Inserts a new key <Key> with value 1. Or increments an existing key by 1.
     */
    public void inc(String key) {
        if (key.length() == 0) {
            return;
        }
        if (map.containsKey(key)) {
            map.put(key, map.get(key) + 1);
        } else {
            map.put(key, 1);
        }
        return;

    }

    /**
     * Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
     */
    public void dec(String key) {
        if (!map.containsKey(key)) {
            return;
        }
        int val = map.get(key);
        if (val == 1) {
            map.remove(key);
        } else {
            map.put(key, val - 1);
        }
        return;

    }

    /**
     * Returns one of the keys with maximal value.
     */
    public String getMaxKey() {
        if (map.size() == 0) {
            return "";
        }
        int max = Integer.MIN_VALUE;
        String maxKey = "";
        for (String key : map.keySet()
        ) {
            if (map.get(key) > max) {
                max = map.get(key);
                maxKey = key;
            }

        }
        return maxKey;
    }

    /**
     * Returns one of the keys with Minimal value.
     */
    public String getMinKey() {
        if (map.size() == 0)
            return "";
        int min = Integer.MAX_VALUE;
        String minKey = "";
        for (String key : map.keySet()) {
            if (map.get(key) < min) {
                min = map.get(key);
                minKey = key;
            }
        }
        return minKey;

    }
}

/**
 * Your AllOne object will be instantiated and called as such:
 * AllOne obj = new AllOne();
 * obj.inc(key);
 * obj.dec(key);
 * String param_3 = obj.getMaxKey();
 * String param_4 = obj.getMinKey();
 */

代码已经上传到git传送门

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值