LeetCode 380: Insert Delete GetRandom O

Posted by Tonisius on Tue, 17 Mar 2020 11:00:15 +0100

Title:

Design a data structure to support the following operations under the average time complexity O(1).

  1. insert(val): when the element val does not exist, insert the item into the collection.
  2. remove(val): remove the item from the collection when the element val exists.
  3. getRandom: returns a random entry from an existing collection. Each element should have the same probability to be returned.

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

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Initializes an empty collection.
RandomizedSet randomSet = new RandomizedSet();

// Insert 1 into the collection. Returns true to indicate that 1 was successfully inserted.
randomSet.insert(1);

// Returns false, indicating that 2 does not exist in the collection.
randomSet.remove(2);

// Insert 2 into the collection. Returns true. The set now contains [1,2].
randomSet.insert(2);

// getRandom should return 1 or 2 at random.
randomSet.getRandom();

// Remove 1 from the collection and return true. The collection now contains [2].
randomSet.remove(1);

// 2 is already in the collection, so false is returned.
randomSet.insert(2);

// Since 2 is the only number in the collection, getRandom always returns 2.
randomSet.getRandom();

Solutions:

  • Require time complexity O(1) insert and delete operation: you can design a hash algorithm from scratch, or you can use the designed hash set / map in the high-level programming language

  • The same probability is required to return elements randomly: hash sets cannot return an element randomly. You can store such as an array with the aid of a sequence, randomly generate index subscripts, and return the corresponding element values

Then we need to use hash map to store the element, key is the element value, value is the index index index value of the element stored in the auxiliary array

Insert operation is the insert operation of array and hash map

The difficulty lies in the deletion operation. First, delete the key value pair in the hash map, and then delete the element value in the array. You can't simply assign an impossible value pseudo deletion, because this pseudo deletion will lead to more and more memory explosion in the array.

Code:

Java:

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.
     * General insert operation
     */
    public boolean insert(int val) {
        if (map.containsKey(val))
            return false;
        map.put(val, list.size()); // value indicates the index subscript stored in the list
        list.add(val); // Add at the end of array list
        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)) // If the key does not exist in the hash map, return False directly
            return false;
        int tmp = list.get(list.size() - 1); // Hold last element value of array
        int index = map.get(val); // Get the index index index of the element to be deleted in the list array
        list.set(index, tmp); // Change the value of this element in the list to the last bit value of the temporary array
        map.put(tmp, index); // Update the index index index of the key value pair representing the last bit of the array in the hash map
        list.remove(list.size() - 1); // Delete last bit of array
        map.remove(val); // Delete the key value pair in the hash map
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        return list.get(rand.nextInt(list.size())); // Generate a random index subscript of size [0, array size)
    }
}

Python:

from random import choice

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.val_map = dict()
        self.val_list = list()

    def insert(self, val: int) -> bool:
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        """
        if val not in self.val_map:
            self.val_map[val] = len(self.val_list) # value indicates index subscript stored in val_list
            self.val_list.append(val) # Add at the end of the array Val list
            return True
        return False

    def remove(self, val: int) -> bool:
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        """
        if val in self.val_map:
            index = self.val_map[val] # Get the index index index of the element to be deleted in the list array
            last_val = self.val_list[-1] # Hold last element value of array
            self.val_list[index] = last_val # Change the value of this element in the list to the last bit value of the temporary array
            self.val_map[last_val] = index # Update the index index index of the key value pair representing the last bit of the array in the hash map
            self.val_map.pop(val) # Delete the key value pair in the hash map
            self.val_list.pop() # Delete last bit of array
            return True
        return False

    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        return choice(self.val_list) # Returns a random element in an array

Welcome to the official account of micro letter: love writing Bug

Topics: Programming Java Python