1. 程式人生 > 其它 >Leetcode 380. Insert Delete GetRandom O(1)

Leetcode 380. Insert Delete GetRandom O(1)

技術標籤:刷題

Leetcode 380. Insert Delete GetRandom O(1)

Implement the RandomizedSet class:

bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.

int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
Follow up: Could you implement the functions of the class with each function works in average O(1) time?

思路:set 可以有O(1),的讀取,但是取一個隨機元素,則需要O(n),需要一個可以記錄index的輔助資料結構,因此用ArrayList 和 HashMap,來記錄元素的index。

重點:
1. list 新增用 add(int index, E element),新增到最後一個位置。
2. 移除元素的時候,將最後的一個元素的位置和將被移除的元素交換位置,O(1)的時間做到Arraylist的移除,set(int index, E element)。

class RandomizedSet {
    
    List<Integer> list;
    Map<
Integer, Integer>
map; Random rand; /** Initialize your data structure here. */ public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); 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) { if (map.containsKey(val)) return false; map.put(val, list.size()); list.add(list.size(), val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if (!map.containsKey(val)) return false; int lastElement = list.get(list.size()-1); int index = map.get(val); list.set(index, lastElement); map.put(lastElement, index); list.remove(list.size()-1); map.remove(val); return true; } /** Get a random element from the set. */ public int getRandom() { return list.get(rand.nextInt(list.size())); } }