LeetCode #1206 Design Skiplist 设计跳表

1206 Design Skiplist 设计跳表

Description:
Design a Skiplist without using any built-in libraries.

A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.

For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:

[图片上传失败...(image-910506-1658460863076)]

Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons

You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).

See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list

Implement the Skiplist class:

Skiplist() Initializes the object of the skiplist.
bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.
void add(int num) Inserts the value num into the SkipList.
bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not exist in the Skiplist, do nothing and return false. If there exist multiple num values, removing any one of them is fine.
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.

Example:

Example 1:

Input
["Skiplist", "add", "add", "add", "search", "add", "search", "erase", "erase", "search"]
[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]
Output
[null, null, null, null, false, null, true, false, true, false]

Explanation

Skiplist skiplist = new Skiplist();
skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0); // return False
skiplist.add(4);
skiplist.search(1); // return True
skiplist.erase(0);  // return False, 0 is not in skiplist.
skiplist.erase(1);  // return True
skiplist.search(1); // return False, 1 has already been erased.

Constraints:

0 <= num, target <= 2 * 10^4
At most 5 * 10^4 calls will be made to search, add, and erase.

题目描述:
不使用任何库函数,设计一个 跳表 。

跳表 是在 O(log(n)) 时间内完成增加、删除、搜索操作的数据结构。跳表相比于树堆与红黑树,其功能与性能相当,并且跳表的代码长度相较下更短,其设计思想与链表相似。

例如,一个跳表包含 [30, 40, 50, 60, 70, 90] ,然后增加 80、45 到跳表中,以下图的方式操作:

[图片上传失败...(image-aa3a8-1658460863076)]

Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons

跳表中有很多层,每一层是一个短的链表。在第一层的作用下,增加、删除和搜索操作的时间复杂度不超过 O(n)。跳表的每一个操作的平均时间复杂度是 O(log(n)),空间复杂度是 O(n)。

了解更多 : https://en.wikipedia.org/wiki/Skip_list

在本题中,你的设计应该要包含这些函数:

bool search(int target) : 返回target是否存在于跳表中。
void add(int num): 插入一个元素到跳表。
bool erase(int num): 在跳表中删除一个值,如果 num 不存在,直接返回false. 如果存在多个 num ,删除其中任意一个即可。
注意,跳表中可能存在多个相同的值,你的代码需要处理这种情况。

示例 :

示例 1:

输入
["Skiplist", "add", "add", "add", "search", "add", "search", "erase", "erase", "search"]
[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]
输出
[null, null, null, null, false, null, true, false, true, false]

解释

Skiplist skiplist = new Skiplist();
skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0);   // 返回 false
skiplist.add(4);
skiplist.search(1);   // 返回 true
skiplist.erase(0);    // 返回 false,0 不在跳表中
skiplist.erase(1);    // 返回 true
skiplist.search(1);   // 返回 false,1 已被擦除

提示:

0 <= num, target <= 2 * 10^4
调用search, add, erase操作次数不大于 5 * 10^4

思路:

Redis 实现跳表
随机给跳表中的结点分配层数, 即这个结点会影响的层数, 实现为 randomLevel(), 在 Redis 中参数 p 为 1 / 4, 最大层数 maxLevel 为 32
结点包含两个参数, 第一个为值, 可以用模板, 本题中只用到正整数值, 可以设置头结点的值为 -1; 第二个值为对应每层之后的直接结点
插入结点时, 每次需要在某层找到刚好不小于结点值的位置, 并将新结点插入到其后, 实现为 find(), 如果找不到, 说明结点值为最大值, 实际上放在空结点的位置
删除时, 在每一层都查找结点值并进行删除, 只要删除了一个结点就返回 true
时间复杂度为 O(m + n ^ 2), 空间复杂度为 O(m + n ^ 2)

代码:
C++:

struct Node
{
    int val;
    vector<Node*> next;
    Node(int _val, int size): val(_val)
    {
        next.resize(size);
    }
};
class Skiplist
{
private:
    Node* head;
    int cur_level;
    constexpr static double P = 0.25;
    constexpr static int MAX_LEVEL = 32;
    
    static int random_level()
    {
        int level = 1;
        while (1.0 * rand() / RAND_MAX < P and level < MAX_LEVEL) ++level;
        return level;
    }
    
    Node* find(Node* node, int level, int val)
    {
        while (node -> next[level] and val > node -> next[level] -> val) node = node -> next[level];
        return node;
    }
public:
    Skiplist() 
    {
        head = new Node(-1, MAX_LEVEL);
        cur_level = 1;
    }
    
    bool search(int target) 
    {
        Node* cur = head;
        for (int i = cur_level - 1; i > -1; i--) 
        {
            cur = find(cur, i, target);
            if (cur -> next[i] and cur -> next[i] -> val == target) return true;
        }
        return false;
    }
    
    void add(int num) 
    {
        int level = random_level();
        Node* new_node = new Node(num, level);
        Node* update_node = head;
        for (int i = cur_level - 1; i > -1; i--) 
        {
            update_node = find(update_node, i, num);
            if (i < level)
            {
                if (!update_node -> next[i]) update_node -> next[i] = new_node;
                else
                {
                    Node* temp = update_node -> next[i];
                    update_node -> next[i] = new_node;
                    new_node -> next[i] = temp;
                }
            }
        }
        if (level > cur_level)
        {
            for (int i = cur_level; i < level; i++) head -> next[i] = new_node;
            cur_level = level;
        }
    }
    
    bool erase(int num) 
    {
        bool flag = false;
        Node* search_node = head;
        for (int i = cur_level - 1; i > -1; i--) 
        {
            search_node = find(search_node, i, num);
            if (search_node -> next[i] and search_node -> next[i] -> val == num) 
            {
                search_node -> next[i] = search_node -> next[i] -> next[i];
                flag = true;
                continue;
            }
        }
        return flag;
    }
};

/**
 * Your Skiplist object will be instantiated and called as such:
 * Skiplist* obj = new Skiplist();
 * bool param_1 = obj->search(target);
 * obj->add(num);
 * bool param_3 = obj->erase(num);
 */

Java:

class Skiplist {
    private static int DEFAULT_MAX_LEVEL = 32;
    private static double DEFAULT_P_FACTOR = 0.25;
    private Node head;
    private int currentLevel;
    
    public Skiplist() {
        head = new Node(-1, DEFAULT_MAX_LEVEL);
        currentLevel = 1;
    }
    
    class Node {
        int val;
        Node[] next;

        public Node(int val, int size) {
            this.val = val;
            this.next = new Node[size];
        }
    }

    public boolean search(int target) {
        Node cur = head;
        for (int i = currentLevel - 1; i > -1; i--) {
            cur = find(cur, i, target);
            if (cur.next[i] != null && cur.next[i].val == target) return true;
        }
        return false;
    }

    private Node find(Node node, int level, int val) {
        while (node.next[level] != null && val > node.next[level].val) node = node.next[level];
        return node;
    }

    private static int randomLevel() {
        int level = 1;
        while (Math.random() < DEFAULT_P_FACTOR && level < DEFAULT_MAX_LEVEL) ++level;
        return level;
    }
    
    public void add(int num) {
        int level = randomLevel();
        Node updateNode = head;
        Node newNode = new Node(num, level);
        for (int i = currentLevel - 1; i > -1; i--) {
            updateNode = find(updateNode, i, num);
            if (i < level) {
                if (updateNode.next[i] == null) updateNode.next[i] = newNode;
                else {
                    Node temp = updateNode.next[i];
                    updateNode.next[i] = newNode;
                    newNode.next[i] = temp;
                }
            }
        }
        if (level > currentLevel) {
            for (int i = currentLevel; i < level; i++) head.next[i] = newNode;
            currentLevel = level;
        }
    }

    public boolean erase(int num) {
        boolean flag = false;
        Node searchNode = head;
        for (int i = currentLevel - 1; i > -1; i--) {
            searchNode = find(searchNode, i, num);
            if (searchNode.next[i] != null && searchNode.next[i].val == num) {
                searchNode.next[i] = searchNode.next[i].next[i];
                flag = true;
                continue;
            }
        }
        return flag;
    }
}

/**
 * Your Skiplist object will be instantiated and called as such:
 * Skiplist obj = new Skiplist();
 * boolean param_1 = obj.search(target);
 * obj.add(num);
 * boolean param_3 = obj.erase(num);
 */

Python:

class Skiplist:

    def __init__(self):
        self.data = defaultdict(int)
        

    def search(self, target: int) -> bool:
        return self.data[target] > 0


    def add(self, num: int) -> None:
        self.data[num] += 1


    def erase(self, num: int) -> bool:
        if (n := self.data[num]) > 0:
            self.data[num] -= 1
        return n > 0



# 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)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,492评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,048评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,927评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,293评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,309评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,024评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,638评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,546评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,073评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,188评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,321评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,998评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,678评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,186评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,303评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,663评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,330评论 2 358

推荐阅读更多精彩内容