Insert Delete GetRandom O(1) | LeetCode 380 | Programming Tutorials

preview_player
Показать описание
In this tutorial, I have discussed how we can implement insert, delete, getRandom() method in O(1) time complexity.

Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if it's not 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.

Рекомендации по теме
Комментарии
Автор

I have seen 3 to 4 videos on this problem. This is one is the best explanation I have seen so far.

sushmasinghSS
Автор

Thank you, Sir! You' deserve more audience.

kartikpant
Автор

"You are Amazing!!", Thnks for the playlist.

barureddy
Автор

class RandomizedSet {

private Set set1;
Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
set1 = new TreeSet();
rand = new Random();
}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
return set1.add(val);
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
return set1.remove(val);

}

/** Get a random element from the set. */
public int getRandom() {
List<Integer> list1 = new ArrayList<Integer>();
list1.addAll(set1);
return

}
}

pradeepmanivelan