380. Insert Delete GetRandom O(1)

因为insert和remove之前要判断是否存在,也就是查找,所以自然的想到的是二分查找。。
代码如下:

from random import randint
class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.lists = []
        

    def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if len(self.lists) == 0:
            self.lists.append(val)
            return True
        flag = 0
        s = 0 
        e = len(self.lists)-1
        m = (s+e) / 2
        while s <= e:
            m = (s+e) / 2
            if self.lists[m] == val:
                flag = 1
                break
            elif self.lists[m] > val:
                e = m-1
            else:
                s = m+1
        if flag == 1:
            return False
        else:
            self.lists = self.lists[:e+1] + [val] + self.lists[s:]
            return True
        

    def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if len(self.lists) == 0:
            return False
        s = 0 
        e = len(self.lists)-1
        while s <= e:
            m = (s+e) / 2
            if self.lists[m] == val:
                self.lists.pop(m)
                return True
            elif self.lists[m] > val:
                e = m-1
            else:
                s = m+1
        return False
                
        

    def getRandom(self):
        """
        Get a random element from the set.
        :rtype: int
        """
        if len(self.lists) == 0:
            return None
        if len(self.lists) == 1:
            return self.lists[0]
        return self.lists[randint(0,len(self.lists)-1)]
        


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

哈希表的方法:
代码如下:

from random import randint
class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.lists = []
        self.zd = {}
        

    def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.zd:
            self.lists.append(val)
            self.zd[val] = len(self.lists) - 1
            return True
        else:
            return False
        

    def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.zd:
            return False
        else:
            self.lists.pop(self.lists.index(val))
            del self.zd[val]
            return True
        

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


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

删除中查找的办法并没有充分利用哈希表中的值,借鉴discussion里面的办法:

from random import randint
class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.lists = []
        self.zd = {}
        

    def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.zd:
            self.lists.append(val)
            self.zd[val] = len(self.lists) - 1
            return True
        else:
            return False
        

    def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.zd:
            return False
        else:
            index = self.zd[val]
            self.lists[index], self.lists[len(self.lists)-1] = self.lists[len(self.lists)-1], self.lists[index]
            self.zd[self.lists[index]] = index
            del self.zd[self.lists[len(self.lists) - 1]]
            self.lists.pop()
            return True
        

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


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

你可能感兴趣的:(380. Insert Delete GetRandom O(1))