跳跃表

应用

应用1:Leetocde1206

题目

1206. 设计跳表

解题思路

参考:

代码

import random
from typing import List


class Skiplist(object):
    # 最大层数
    DEFAULT_MAX_LEVEL = 32
    # 随机层数概率
    DEFAULT_P_FACTOR = 0.25

    class Node(object):
        def __init__(self, value: int = None, size: int = 0):
            self.value = value
            self.size = size
            self.next: List["Node"] = [None for _ in range(size)]

        def __str__(self):
            return "Node<value=%s, size=%s>" % (self.value, self.size)

    def __init__(self):
        self.head = Skiplist.Node(size=self.DEFAULT_MAX_LEVEL)
        self.current_level = 1

    def search(self, target: int) -> bool:
        search_node = self.head
        for i in range(self.current_level - 1, -1, -1):
            search_node = self._find_closest(search_node, i, target)
            if search_node.next[i] and search_node.next[i].value == target:
                return True
        return False

    def add(self, num: int) -> None:
        level = self._random_level()
        update_node = self.head
        new_node = self.Node(num, level)

        for i in range(self.current_level - 1, -1, -1):
            update_node = self._find_closest(update_node, i, num)
            if i < level:
                if not update_node.next[i]:
                    update_node.next[i] = new_node
                else:
                    temp = update_node.next[i]
                    update_node.next[i] = new_node
                    new_node.next[i] = temp

        if level > self.current_level:
            for i in range(self.current_level, level):
                self.head.next[i] = new_node
            self.current_level = level
        return

    def erase(self, num: int) -> bool:
        flag = False
        search_node = self.head
        for i in range(self.current_level - 1, -1, -1):
            search_node = self._find_closest(search_node, i, num)
            if search_node.next[i] and search_node.next[i].value == num:
                search_node.next[i] = search_node.next[i].next[i]
                flag = True
                continue

        return flag

    @staticmethod
    def _find_closest(node: Node, level_index: int, value: int):
        while node.next[level_index] and value > node.next[level_index].value:
            node = node.next[level_index]
        return node

    @classmethod
    def _random_level(cls):
        level = 1
        while random.random() < cls.DEFAULT_P_FACTOR and level < cls.DEFAULT_MAX_LEVEL:
            level += 1
        return level



# Your Skiplist object will be instantiated and called as such:
# obj = Skiplist()
# param_1 = obj.search(target)
# obj.add(num)
# param_3 = obj.erase(num)
posted @ 2023-03-09 20:08  LARRY1024  阅读(15)  评论(0编辑  收藏  举报