题目
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
题意解析
要求实现上述的三个操作,且操作时间为O(1)的操作时间。使用HashMap保存输入的数字的index,用ArrayList保存数组。一个值得注意的问题是,有一个getRandom的操作,计划是根据Random类的nextInt方法来获得下标,然后从ArrayList中返回数据,故应该保持ArrayList中的index的连续的,一个简单的做法是将删除的元素由最后一个元素取代,并删除原最后元素,保证size-1;
Code
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created by loveqh on 2016/8/9.
*/
public class RandomizedSet {
private HashMap<Integer, Integer> hashMap;
private ArrayList<Integer> arrayList;
/**
* Initialize your data structure here.
*/
public RandomizedSet() {
hashMap = new HashMap<>();
arrayList = new ArrayList<>();
}
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
*/
public boolean insert(int val) {
if (hashMap.containsKey(val)) {
return false;
} else {
hashMap.put(val, hashMap.size());
arrayList.add(val);
return true;
}
}
/**
* Removes a value from the set. Returns true if the set contained the specified element.
*/
public boolean remove(int val) {
if (!hashMap.containsKey(val)) {
return false;
} else {
// V = hashMap.remove(K)
int index = hashMap.remove(val);
/**
* 要求getRandom的数据为连续 ,故将删除的位置和数组的最后一个元素填补
*/
if (index < arrayList.size() - 1) {
//用最后一个数取代index位置的元素
arrayList.set(index, arrayList.get(arrayList.size() - 1));
//修改KeyValue
hashMap.put(arrayList.get(arrayList.size() - 1), index);
}
//删除最后一个元素
arrayList.remove(arrayList.size() - 1);
return true;
}
}
/**
* Get a random element from the set.
*/
Random random = new Random();
public int getRandom() {
return arrayList.get(random.nextInt(arrayList.size()));
}
}
/**
* 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();
*/
提交的时候一个值得注意的点
一定要在public class 前使用
import java.util.Random
不然会产生编译错误。我也真是服了。