设计RandomPool

题目:设计一种结构, 在该结构中有如下三个功能:

insert(key): 将某个key加入到该结构, 做到不重复加入。
delete(key): 将原本在结构中的某个key移除。
getRandom(): 等概率随机返回结构中的任何一个key。


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

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

        public void insert(K key) {
            if (!this.keyIndexMap.containsKey(key)) {
                this.keyIndexMap.put(key, this.size);
                this.indexKeyMap.put(this.size++, key);
            }
        }

//1.首先得到要被删除元素的index,
//2.通过最后一个元素的下标,得到最后一个元素是什么
//3.然后在调整最后一个元素的value值
//4.最后要注意删除
        public void delete(K key) {
            if (this.keyIndexMap.containsKey(key)) {
                int deleteIndex = this.keyIndexMap.get(key);
                int lastIndex = --this.size;
                K lastKey = this.indexKeyMap.get(lastIndex);
                this.keyIndexMap.put(lastKey, deleteIndex);
                this.indexKeyMap.put(deleteIndex, lastKey);
                this.keyIndexMap.remove(key);
                this.indexKeyMap.remove(lastIndex);
            }
        }

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

    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,212评论 2 89
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,694评论 18 399
  • Do not linger to gather flowersto keep them, but walk on ...
    不许抢我西瓜阅读 1,607评论 0 1
  • 剑客背着一柄剑,斜斜地指向天空。他只有这么一柄剑,就好像辽远的地平线只有一轮落日般。他背着一柄剑向着落日而行,不疾...
    王无求阅读 3,677评论 1 3
  • (二)学生工作 经过一段时间的了解,我渐渐明白办公室这个部门的性质,正因为它的特殊性,所以我很...
    伊卡罗斯阅读 1,463评论 2 2

友情链接更多精彩内容