Algorithm: O(1) time to insert, delete and get random elements---hash table + dynamic array

Insert image description here


1. Topic:

Implementation RandomizedSetclass:

  • RandomizedSet()initialize RandomizedSetobject
  • bool insert(int val)When the element valdoes not exist, insert the item into the collection and return true; otherwise, return false.
  • bool remove(int val)If element valexists, remove the item from the collection and return true; otherwise, return false.
  • int getRandom()Returns a random item from an existing collection (the test case guarantees that at least one element is present in the collection when this method is called). Each element should have the same probability of being returned.

You must implement all functions of the class and satisfy the average time complexity of each function O(1).


2. Analysis features:

  • Question requirements: The time complexity of inserting, deleting and obtaining random elements is O(1)

  • In terms of traversing and retrieving queries, the time complexity of arrays can be O(1), but insertion and deletion require judging whether val exists, resulting in insertion and deletion exceeding O(1).

  • Hash tables can complete insertion and deletion operations in O(1) time

  • So: hash table + dynamic array

A variable-length array can complete the operation of obtaining random elements in O(1) time, but because it cannot determine whether the element exists in O(1) time, the insertion and deletion operations cannot be completed in O(1) time. A hash table can complete insertion and deletion operations in O(1) time, but because it cannot locate a specific element based on the subscript, it cannot complete the acquisition of random elements in O(1) time. In order to meet the time complexity of inserting, deleting and obtaining random elements, it is necessary to combine variable-length arrays and hash tables. Elements are stored in the variable-length array, and each element is stored in the hash table in a variable-length manner. Subscript in the array.

During the insertion operation, first determine whether val is in the hash table. If it already exists, return false. If it does not exist, insert val. The operation is as follows:

Add val at the end of the variable-length array;
the length of the variable-length array before adding val is the subscript index where val is located, and store val and subscript index in the hash table;
return true.

When deleting, first determine whether val is in the hash table. If it does not exist, return false. If it exists, delete val. The operation is as follows:

Obtain the subscript index of val from the hash table;
move the last element last of the variable-length array to the subscript index, and update the subscript of last to index in the hash table; delete the last element in the
variable-length array Element, deletes val in the hash table;
returns true.

The focus of the deletion operation is to move the last element of the variable-length array to the subscript of the element to be deleted, and then delete the last element of the variable-length array. The time complexity of this operation is O(1), and it can ensure that the subscripts of all elements in the variable-length array are continuous after the deletion operation, which is convenient for insertion operations and acquisition of random elements.

When obtaining a random element, since the subscripts of all elements in the variable-length array are consecutive, a subscript is randomly selected and the element at that subscript in the variable-length array is returned.


3. Code:

class RandomizedSet {
    
    
    List<Integer> nums;
    Map<Integer, Integer> indices;
    Random random;

    public RandomizedSet() {
    
    
        nums = new ArrayList<Integer>();
        indices = new HashMap<Integer, Integer>();
        random = new Random();
    }

    public boolean insert(int val) {
    
    
        if (indices.containsKey(val)) {
    
    
            return false;
        }
        int index = nums.size();
        nums.add(val);
        indices.put(val, index);
        return true;
    }

    public boolean remove(int val) {
    
    
        if (!indices.containsKey(val)) {
    
    
            return false;
        }
        int index = indices.get(val);
        int last = nums.get(nums.size() - 1);
        nums.set(index, last);
        indices.put(last, index);
        nums.remove(nums.size() - 1);
        indices.remove(val);
        return true;
    }

    public int getRandom() {
    
    
        int randomIndex = random.nextInt(nums.size());
        return nums.get(randomIndex);
    }
}

4. Complexity analysis:

  • Time complexity: The time complexity of initialization and various operations is O(1).

    Space complexity: O(n), where n is the number of elements in the set. Arrays and hash tables that store elements require O(n) space.


5. Summary:

The design of the average time complexity of O(1) is inseparable from the hash table.
Generally, insertion, deletion, and retrieval can be implemented with arrays, so just choose arrays, which is simpler.
You can combine the two data structures according to the topic, such as: array + hash table




If this article is helpful to you, please remember to give Yile a like, thank you!

Guess you like

Origin blog.csdn.net/weixin_45630258/article/details/133265909