Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 380 · Design

Insert Delete GetRandom O(1)

LeetCode 380 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

List + index map; delete by swapping with the last element.

நடுத்தரம்ArrayHash TableMathDesignRandomized
LeetCode இல் திற ↗

நான் Insert Delete GetRandom O(1) (LeetCode 380) ஐ இப்படித் தீர்த்தேன் — Design பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.

Approach

  1. 1

    insert: reject duplicates, append, record the index.

  2. 2

    remove: look up the index, overwrite it with the last value, update that value's index, pop the end.

  3. 3

    getRandom: random.choice on the list.

நான் எப்படித் தீர்த்தேன்

Array + hash mapPythonO(1) per op
class RandomizedSet:

    def __init__(self):
        self.data = []
        self.loc_map={}
    def insert(self, val: int) -> bool:
        if val in self.loc_map:
            return False
        self.data.append(val)
        self.loc_map[val]=len(self.data)-1
        return True
    def remove(self, val: int) -> bool:
        if val not in self.loc_map:
            return False
        remove_item_index = self.loc_map.get(val)
        last_item = self.data[-1]
        self.data[remove_item_index]=last_item
        self.loc_map[last_item]=remove_item_index
        del self.loc_map[val]
        self.data.pop()
        return True

    def getRandom(self) -> int:
        return random.choice(self.data)


# 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()
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Insert Delete GetRandom O(1) — அடிக்கடி கேட்கப்படும் கேள்விகள்

Insert Delete GetRandom O(1) பின்னாலுள்ள intuition என்ன?

A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.

Insert Delete GetRandom O(1) (LeetCode 380) ஐ எப்படித் தீர்ப்பது?

1. insert: reject duplicates, append, record the index. 2. remove: look up the index, overwrite it with the last value, update that value's index, pop the end. 3. getRandom: random.choice on the list.

Insert Delete GetRandom O(1) இன் time மற்றும் space complexity என்ன?

Time: O(1) average per operation. Space: O(n). (Accepted approach: Array + hash map.)

Insert Delete GetRandom O(1) இல் பொதுவான தவறுகள் என்ன?

Update the moved element's index before deleting the removed key (order matters when removing the last element).