哈希结构算法

48 篇文章 0 订阅
46 篇文章 0 订阅

【题目】
设计一种结构满足如下3个功能
insert(key):将某个key加入到该结构,做到不重复添加
delete(key):将原本在结构中的某个key移除
getRandom():等概率随机返回结构中任意key
【要求】
3个方法的时间复杂度要求O(1)

public class RandomPool {

    public static class Pool<K>{
        private HashMap<K, Integer> keyIndexMap;
        private HashMap<Integer, K> indexKeyMap;
        private int size;

        public Pool() {
            this.keyIndexMap = new HashMap<>();
            this.indexKeyMap = new HashMap<>();
            this.size = 0;
        }

        public void insert(K key){
        	//控制不重复添加
            if (keyIndexMap.containsKey(key)){
                return;
            }
            keyIndexMap.put(key, size);
            indexKeyMap.put(size++, key);
        }

        public void delete(K key){

            if (!keyIndexMap.containsKey(key)){
                return;
            }
            //要删除的
            int deleteKIndex = keyIndexMap.get(key);
            int lastIndex = --size;
            //最后一个数据
            K lastKey = indexKeyMap.get(lastIndex);
            keyIndexMap.put(lastKey, deleteKIndex);
            indexKeyMap.put(deleteKIndex, lastKey);
            keyIndexMap.remove(key);
            indexKeyMap.remove(lastIndex);
        }

        public K getRandom(){
            if (size == 0){
                return null;
            }
            int randomIndex = (int) (Math.random() * size);
            return this.indexKeyMap.get(randomIndex);
        }
    }

    public static void main(String[] args) {
        Pool<String> pool = new Pool<>();
        pool.insert("hi");
        pool.insert("hi");
        pool.insert("happy");
        pool.insert("every");
        pool.insert("day");
        pool.delete("every");
        String random = pool.getRandom();
        System.out.println(random);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值