设计RandomPool

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

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


public static class Pool {
        private HashMap keyIndexMap;
        private HashMap indexKeyMap;
        private int size;

        public Pool() {
            this.keyIndexMap = new HashMap();
            this.indexKeyMap = new HashMap();
            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);
        }

    }

你可能感兴趣的:(设计RandomPool)