Can we use HashSet? I don't understand the time complexity of HashSet

  • 0

    class RandomizedSet {

    /** Initialize your data structure here. */
    Set<Integer> set;
    ArrayList<Integer> array;
    public RandomizedSet() {
    	set=new HashSet<Integer>();
        array=new ArrayList<Integer>();
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
    	boolean flag=set.add(val);
    	return flag;
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
    	boolean flag=set.remove(val);
    	Integer x=new Integer(val);
    	return flag;
    /** Get a random element from the set. */
    public int getRandom() {
    	int size=set.size();
    	Random random=new Random();
    	int x=random.nextInt(size-1);
    	return array.get(x);



Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.