Leetcode 380. Insert Delete GetRandom O(1) (python+cpp)

题目

Leetcode 380. Insert Delete GetRandom O(1) (python+cpp)_第1张图片

解法:list+hashmap

list储存所有元素
hashmap中key为值,value为他储存在list中的index
insert是O(1)显而易见,关键是delete如何做到O(1)。
普通的删除元素操作比如erase是O(n)的。基本思想是替换和pop操作都是O(1)的
根据hashmap储存的值可以知道要删除的元素在哪个位置,把这个位置的元素用最后一个元素替换,然后把最后一个元素pop出来,同时更新hahsmap中最后一个元素储存的index

import random
class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dict = {
     }
        self.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 in self.dict:
            return False
        self.dict[val] = len(self.list)
        self.list.append(val)
        return True

    def remove(self, val: int) -> bool:
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        """
        if val not in self.dict:
            return False
        last_val, idx = self.list[-1], self.dict[val]
        # put the last element to the place where the val we want to delete, in this way the val we want to delete is gone
        self.list[idx] = last_val
        # update the index of the last element as the changed idx
        self.dict[last_val] = idx
        # pop out the last element
        self.list.pop()
        # delete the val:idx pair
        del self.dict[val]
        return True

    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        # return random.choice(self.list)
        return self.list[random.randint(0,len(self.list)-1)]

C++版本

class RandomizedSet {
     
public:
    vector<int> nums;
    unordered_map<int,int> seen;
    /** Initialize your data structure here. */
    RandomizedSet() {
     
        
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
     
        if(seen.find(val) != seen.end()) return false;
        seen[val] = nums.size();
        nums.push_back(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
     
        if(seen.find(val) == seen.end()) return false;
        int last_val = nums.back();
        int idx = seen[val];
        nums[idx] = last_val;
        seen[last_val] = idx;
        nums.pop_back();
        seen.erase(val);
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
     
        return nums[rand() % nums.size()];
    }
};

你可能感兴趣的:(Leetcode,其他类型题目,python,c++,leetcode)