Разработайте структуру данных, которая поддерживает все последующие операции за среднее O(1) время.

  1. insert(val): вставляет элемент val в набор, если он еще не присутствует.
  2. remove(val): Удаляет элемент val из набора, если он присутствует.
  3. getRandom: возвращает случайный элемент из текущего набора элементов. Каждый элемент должен иметь одинаковую вероятность быть возвращенным.

Пример:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);
// Returns false as 2 does not exist in the set.
randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
// 2 was already in the set, so return false.
randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

Вот мое решение: он успешно прошел 17/18 тестов в LeetCode.

import java.util.*;
public class SetTest{
public static void main(String[] args){
 System.out.println("I am OK");
 RandomizedSet rSet = new RandomizedSet();
 System.out.println(rSet.insert(10));
 System.out.println(rSet.insert(10));
 System.out.println(rSet.insert(11));
System.out.println(rSet.insert(12));
 System.out.println(rSet.insert(13));
System.out.println(rSet.getRandom());
}
static class RandomizedSet {
 HashSet<Integer> set;
/** Initialize your data structure here. */
    public RandomizedSet() {
     set = new HashSet<Integer>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
         return set.add(val);
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
     if(!set.isEmpty()){
      return set.remove(val);
     }
        return false;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
     int size  = set.size();
     int targetIndex = getRandomNumberInRange(0,size-1);
     return set.toArray(new Integer[set.size()])[targetIndex];
    }
private static int getRandomNumberInRange(int min, int max) {
     if(max==0){
      return 0;
     }
  Random rand = new Random();
  int  n = rand.nextInt(max) + min;
  return n;
  
 }
}
}

Улучшение может быть сделано с помощью флага, определяющего преобразование в массив или нет, но требуется дополнительная память.

Примечание: Ваши комментарии будут высоко оценены.