首页 > 学院 > 开发设计 > 正文

LeetCode 380. Insert Delete GetRandom O(1) 题解

2019-11-06 07:36:12
字体:
来源:转载
供稿:网友
  题目链接:点击打开链接   解题思路:使用数组可以在O(1)时间复杂度内实现查询(在这里就是:getRandom方法首先产生一个随机下标,然后通过下标访问数据,O(1));                     但是正常来说数组不能在O(1)时间复杂度内完成插入删除,此处的处理是,                     对于插入:此题没有限制在指定位置插入数据,如果在数组的最后插入,则时间复杂度为O(1),所以关键是要在O(1)时间内判断待插入的数值是否已经存在。如果使用HashMap来保存<value,index>键值对,那么就可以用HashMap的containsKey(value)方法,在O(1)时间内判断出该值是否已经存在。                     对于删除,一种可以在O(1)时间内完成删除操作的方式是,使用数组中的最后一个数来覆盖待删除的数,但是此时需要更新HashMap。java参考代码如下:
import java.util.ArrayList;import java.util.HashMap;import java.util.Random;public class RandomizedSet {		PRivate ArrayList<Integer> arrayList;	private HashMap<Integer, Integer> map;    /** Initialize your data structure here. */    public RandomizedSet() {        arrayList = new ArrayList<Integer>();        map = new HashMap<Integer, Integer>();    }        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */    public boolean insert(int val) {    	// 首先判断待插入的数据是否已经存在    	if(map.containsKey(val)){    		return false;    	}    	// 不存在,插入新元素    	int index = arrayList.size();    	arrayList.add(val);    	map.put(val, index);    	return true;    }        /** Removes a value from the set. Returns true if the set contained the specified element. */    public boolean remove(int val) {        if(map.containsKey(val)){        	int removeIndex = map.get(val);        	// 将该元素在Map所对应的<value,index>键值对删除        	map.remove(val);        	if(!map.isEmpty()){        		// 使用数组的最后一个元素覆盖待删除的元素            	int last = arrayList.get(arrayList.size()-1);            	// 更新(原)最后一个元素在Map中的index值            	map.put(last, removeIndex);            	arrayList.set(removeIndex, last);        	} else {				arrayList.remove(0);			}        	return true;        } else {        	return false;        }    }        /** Get a random element from the set. */    public int getRandom() {    	if(map.isEmpty()){    		return -1;    	}    	Random random = new Random();        int index = random.nextInt(arrayList.size());        return arrayList.get(index);    }}
上一篇:线程的控制(常见方法)

下一篇:结构

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表