java_Hashmap_3_function_O(1)

学习来自左神

【要求:】

// 设计一个结构,

//3个功能

//insert(key):将某个key加入到该结构,做到不重复,

//delete(key):将原本在结构中的某个key去除

//getRandom():等概率随机返回结构中的任何一个key

//要求:

//3个功能时间复杂度为O(1), 不能遍历

【代码:】

import java.util.HashMap;


// 设计一个结构,
//3个功能 
//insert(key):将某个key加入到该结构,做到不重复,
//delete(key):将原本在结构中的某个key去除
//getRandom():等概率随机返回结构中的任何一个key
//要求:
//3个功能时间复杂度为O(1), 不能遍历


// 先忽略remove的行为,只考虑插入操作insert(),与getRandom(),
public class HashMap_Random_Pool {
	
	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);
			}
		}

		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); // 0 ~ size -1
			return this.indexKeyMap.get(randomIndex);
		}

	}
	
	
	
//	
//	// 初始化,定义2个Hashmap与一个size变量
//	public static class Poll<K>{
//		private HashMap<String, Integer> map1;
//		private HashMap<Integer, String> map2;
//		private int size;
//		
//		public Poll() {
//			this.map1 = new HashMap<String, Integer>();
//			this.map2 = new HashMap<Integer, String>();
//			this.size = 0;
//		}
//		
//		//添加insert()的功能
//		public void add (String str) {
//			map1.put(str, size);
//			map2.put(size, str);
//			size++;	
//		}
//		
//		// 添加getRandom()功能, 注意这里可以等概率,因为我数字增加,通过size可以知道长度,通过Math.random()可以知道返回等概率
//		public String getRandom() {
//			if (size == 0) {
//				return null;
//			}
//			int index = (int)(Math.random()*size);
//			return map2.get(index);
//			
//		}
//			
//	}
	
	
	public static void main(String[] args) {
		Pool<String> pool = new Pool<String>();
		pool.insert("zuo");
		pool.insert("cheng");
		pool.insert("yun");
		System.out.println(pool.getRandom());
		System.out.println(pool.getRandom());
		System.out.println(pool.getRandom());
		System.out.println(pool.getRandom());
		System.out.println(pool.getRandom());
		System.out.println(pool.getRandom());

	}

}

猜你喜欢

转载自blog.csdn.net/sinat_15355869/article/details/82260995