LeetCode //380. Insert Delete GetRandom O(1)

380. Insert Delete GetRandom O(1)

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.

  • *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.

You must implement the functions of the class such that each function works in average O(1) time complexity.

 

Example 1:

Input:
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
Output:
[null, true, false, true, 2, true, false, 2]
Explanation:
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

Constraints:

  • − 2 31 < = v a l < = 2 31 − 1 -2^{31} <= val <= 2^{31} - 1 231<=val<=2311
  • At most 2 ∗ 1 0 5 2 * 10^5 2105 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

From: LeetCode
Link: 380. Insert Delete GetRandom O(1)


Solution:

Ideas:
It uses a dynamic array (a resizable array) to store the elements of the set. The insert, remove, and getRandom operations are implemented as follows:
1. randomizedSetInsert: This function checks if the element to be inserted is already in the array by performing a linear search over the array. If the element is found, it returns false to indicate that the element was not inserted. If the element is not found, it appends it to the end of the array and returns true to indicate that the element was successfully inserted. If the array is full (i.e., its size is equal to its capacity), it is resized to double its current capacity before the new element is appended.
2. randomizedSetRemove: This function also checks if the element to be removed is in the array by performing a linear search over the array. If the element is not found, it returns false to indicate that the element was not removed. If the element is found, it removes it by replacing it with the last element in the array and reducing the size of the array by one. It then returns true to indicate that the element was successfully removed.
3. randomizedSetGetRandom: This function returns a random element from the array. It does this by generating a random index into the array and returning the element at that index.
Note that the randomizedSetInsert and randomizedSetRemove functions use a linear search to check if an element is in the array. This takes O(n) time in the worst case, where n is the number of elements in the array. The randomizedSetGetRandom function, on the other hand, runs in O(1) time, as it simply generates a random index and returns the element at that index.
The RandomizedSet object also includes a randomizedSetCreate function to initialize the object and a randomizedSetFree function to deallocate the memory used by the object.
The key point is that this code doesn’t meet the problem’s requirement that all operations should be average O(1) time complexity. This solution has O(n) complexity for insert and remove operations because it uses a linear search to find elements in the array. However, it’s a simplified solution that only uses built-in C language features, without requiring a hash table or other more complex data structure.
Code:
typedef struct {
    int* array;
    int size;
    int capacity;
} RandomizedSet;

RandomizedSet* randomizedSetCreate() {
    RandomizedSet* obj = (RandomizedSet*) malloc(sizeof(RandomizedSet));
    obj->array = (int*) malloc(10 * sizeof(int));
    obj->size = 0;
    obj->capacity = 10;
    srand(time(NULL));  
    return obj;
}

bool randomizedSetInsert(RandomizedSet* obj, int val) {
    for (int i = 0; i < obj->size; i++) {
        if (obj->array[i] == val) {
            return false;
        }
    }
    if (obj->size >= obj->capacity) {
        obj->capacity *= 2;
        obj->array = (int*) realloc(obj->array, obj->capacity * sizeof(int));
    }
    obj->array[obj->size] = val;
    obj->size++;
    return true;
}

bool randomizedSetRemove(RandomizedSet* obj, int val) {
    for (int i = 0; i < obj->size; i++) {
        if (obj->array[i] == val) {
            obj->array[i] = obj->array[obj->size - 1];
            obj->size--;
            return true;
        }
    }
    return false;
}

int randomizedSetGetRandom(RandomizedSet* obj) {
    int randIndex = rand() % obj->size;
    return obj->array[randIndex];
}

void randomizedSetFree(RandomizedSet* obj) {
    free(obj->array);
    free(obj);
}

/**
 * Your RandomizedSet struct will be instantiated and called as such:
 * RandomizedSet* obj = randomizedSetCreate();
 * bool param_1 = randomizedSetInsert(obj, val);
 
 * bool param_2 = randomizedSetRemove(obj, val);
 
 * int param_3 = randomizedSetGetRandom(obj);
 
 * randomizedSetFree(obj);
*/

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)