拿力扣的题目距离
class RandomizedSet {
private Set aset=new HashSet<Integer>();
public RandomizedSet() {
}
public boolean insert(int val) {
if(aset.contains(val)){
return false;
}
else{
aset.add(val);
return true;
}
}
public boolean remove(int val) {
if(aset.contains(val)){
aset.remove(val);
return true;
}
else{
return false;
}
}
public int getRandom() {
double t=Math.random();
int i=(int)Math.floor(t*aset.size());
Integer[] arr1=new Integer[aset.size()];
Integer[] arr2=(Integer[])aset.toArray(arr1);
return arr1[i];
}
}
/**
* 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();
*/
看上文中红色字部分即可发现
1、先根据传入set的元素类型,创建对应基本类型的对象类型的数组
2、这个新建的数组要以set.size()跟set一样的大小
3、然后在调用set.toArray()括号中写入这个数组
4、再声明一个数组用来赋值
5、赋值时记的强转