设计RandomPool结构

    设计RandomPool结构
    【题目】 设计一种结构,在该结构中有如下三个功能:
    insert(key):将某个key加入到该结构,做到不重复加入。
    delete(key):将原本在结构中的某个key移除。 getRandom():
    等概率随机返回结构中的任何一个key。

    【要求】 Insert、delete和getRandom方法的时间复杂度都是O(1)

import java.util.HashMap;
import java.util.Random;
public class C01_RandomPoll {
	public static class Pool<Key>{
		//HashMap<K, String>这里的K表示只要是同一种类型就OK了,但并没有指定是哪一种类型
		//例如我需要放String的类型,那第一个放进去的时候,K就被指定为String 了
		//理论上是更为强大的
		HashMap<Key, Integer>keyIndexMap; 
		HashMap<Integer, Key>indexKeyMap; 
		int size;
		public Pool(){
			keyIndexMap = new HashMap<Key, Integer>();
			indexKeyMap = new HashMap<Integer, Key>();
		}
		//插入到pool
		public void insert(Key k){
			keyIndexMap.put(k, size);
			indexKeyMap.put(size++, k);
		}
		//删除(这个结合文末的图片提示来看)
		public void delete(Key key){
			if(!keyIndexMap.containsKey(key)){
				return ;
			}
			int lastIndex = --this.size;
			int deleteIndex = keyIndexMap.get(key);
			Key lastKey = indexKeyMap.get(lastIndex);
			keyIndexMap.put(lastKey, deleteIndex);
			indexKeyMap.put(deleteIndex, lastKey);
			keyIndexMap.remove(lastKey);
		}
		//获取随机
		public Key getRandom(){
			if(size==0){
				return null;
			}
			Random random = new Random();
			int index = random.nextInt(keyIndexMap.size());
			return indexKeyMap.get(index);
		}
		//test
		public static void main(String[] args) {
			Pool<String> pool = new Pool<String>();
			pool.insert("laoganma");
			pool.insert("nengandie");
			pool.insert("yyziii");
			pool.insert("aaaaaa");
			for (int i = 0; i < 10; i++) {
				System.out.println(pool.getRandom());
			}
			pool.delete("nengandie");
			System.out.println("=======");
			for (int i = 0; i < 10; i++) {
				System.out.println(pool.getRandom());
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值