Question:
Design a data structure that supports all following operations in average O(1) time.
insert(val)
: Inserts an item val to the set if not already present.remove(val)
: Removes an item val from the set if present.getRandom
: Returns a random element from current set of elements. Each element must have the same probability of being returned.
Solution:这道题的remove部分有很多可以深究的部分~~不可以单纯的用remove
public class RandomizedSet {
HashMap<Integer,Integer> map = new HashMap<>();
ArrayList<Integer> arr = new ArrayList<>();
/** Initialize your data structure here. */
public RandomizedSet() {
}
/** 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))
{
map.put(val,arr.size());
arr.add(val);
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val))
{
// arr.remove(arr.indexOf(val)); //??????????this is correct
// arr.remove(val);//this is wrong!!
// arr.remove((Integer)val); //this is correct!!
// arraylists是一个链表,这样删除了元素,但是未改变迭代的下标,这样当迭代到最后一个的时候就会抛异常咯。
/* Iterator<Integer> iter = arr.iterator();
while (iter.hasNext())
{
if (iter.next().equals(val))
iter.remove();
}*/
//针对arraylist移到最后一个d再删
if(val!=arr.get(arr.size()-1))
{
int loc=map.get(val);//loc为val在map中的位置,也是val在arraylist中的位置
int lastone=arr.get(arr.size()-1);//获取arraylist中最后一个位置的元素值
map.put(lastone, loc); //这步已经进行了删除
arr.set(loc, lastone ); //这步也已经作了删除
}
arr.remove(arr.size()-1);
map.remove(val);
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
if(arr.size() != 0)
return arr.get((int)(Math.random()*(arr.size())));
return 0;
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
javadoc中remove有两种方法
public E remove(int index);
public boolean remove(Object o);
参考:http://shmilyaw-hotmail-com.iteye.com/blog/1447631
其实还有一个方法,是把要删除的移到最后一个位置
//针对arraylist移到最后一个d再删 if(val!=arr.get(arr.size()-1)) { int loc=map.get(val);//loc为val在map中的位置,也是val在arraylist中的位置 int lastone=arr.get(arr.size()-1);//获取arraylist中最后一个位置的元素值 map.put(lastone, loc); //这步已经进行了删除 arr.set(loc, lastone ); //这步也已经作了删除 } arr.remove(arr.size()-1); map.remove(val); return true;
map.put(value,key);
arr.set(position, value);
next()获得序列中的下一个元素。 hasNext()检查序列中是否还有元素。 remove()将上一次返回的元素从迭代器中移除。
关于arrylist
http://blog.csdn.net/lazy_p/article/details/7365324
http://swiftlet.net/archives/743