点击打开链接
//set的使用
class RandomizedSet {
public:
set<int> values;
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if(values.find(val) != values.end()){
return false;
}
values.insert(values.begin(), val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if(values.find(val) != values.end()){
values.erase(val);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
int r = rand()%values.size();
set<int>:: iterator it;
int i=0;
for(it =values.begin(); it!=values.end(); it++){
if(i==r){
return *it;
}
i+=1;
}
return 0;
}
};