LeetCode 1206. Design Skiplist

news/发布时间2024/5/20 13:01:33

原题链接在这里:https://leetcode.com/problems/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:


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 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 * 104
  • At most 5 * 104 calls will be made to searchadd, and erase.

题解:

The skiplist is multiple layers of linked lists. Each layer list skips over a subset of the elements in the list below it.

We begin with Node class containing value, next pointed node, down pointed node. next is the same as regular list. down is pointing to a copy node having the same value in the below layer list.

When adding node, create a stack to keep track of the path taken during the search. As we may need to insert new value at multiple layers. This stack is used when we track back and decide if we need to add a copy node after these tranversed layers.

Traverse starting from the head of topmost list.

Move right until finding a node whose next value is greater than the target.
Then move down one level and repeat the process.
Now we hit the bottom laywer and find the right position. In sert the value and traverse back up with a 50% chance of inserting it into above levels.

If at the top level, and insert is still true, we add a new level on the top.

Search and erase are similar.

Time Complexity: search, O(long). add, O(logn). erase, O(logn). Ideally at each layer above, there is half less nodes. The height of the laywers is logn.

Space: O(n). n is the number of nodes at the bottom laywer. Each layer up has one half nodes. n + n/2 + n/4 +... < 2n.

AC Java:

 1 class Skiplist {
 2     Node head;
 3     Random rand;
 4 
 5     public Skiplist() {
 6         head = new Node(-1, null, null);
 7         rand = new Random();
 8     }
 9     
10     public boolean search(int target) {
11         Node cur = head;
12         while(cur != null){
13             while(cur.next != null && cur.next.val < target){
14                 cur = cur.next;
15             }
16             if(cur.next != null && cur.next.val == target){
17                 return true;
18             }
19 
20             cur = cur.down;
21         }
22 
23         return false;
24     }
25     
26     public void add(int num) {
27         Node cur = head;
28         Stack<Node> stk = new Stack<>();
29         while(cur != null){
30             while(cur.next != null && cur.next.val < num){
31                 cur = cur.next;
32             }
33             stk.push(cur);
34             cur = cur.down;
35         }
36 
37         boolean insert = true;
38         Node down = null;
39         while(insert && !stk.isEmpty()){
40             cur = stk.pop();
41             cur.next = new Node(num, cur.next, down);
42             down = cur.next;
43             insert = rand.nextDouble() < 0.5;
44         }
45 
46         if(insert){
47             head = new Node(-1, null, head);
48         }
49     }
50     
51     public boolean erase(int num) {
52         Node cur = head;
53         boolean found = false;
54         while(cur != null){
55             while(cur.next != null && cur.next.val < num){
56                 cur = cur.next;
57             }
58 
59             if(cur.next != null && cur.next.val == num){
60                 found = true;
61                 cur.next = cur.next.next;
62             }
63 
64             cur = cur.down;
65         }
66 
67         return found;
68     }
69 }
70 
71 class Node{
72     int val;
73     Node next;
74     Node down;
75     public Node(int val, Node next, Node down){
76         this.val = val;
77         this.next = next;
78         this.down = down;
79     }
80 }
81 
82 /**
83  * Your Skiplist object will be instantiated and called as such:
84  * Skiplist obj = new Skiplist();
85  * boolean param_1 = obj.search(target);
86  * obj.add(num);
87  * boolean param_3 = obj.erase(num);
88  */

类似Design Linked List.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ulsteruni.cn/article/68134436.html

如若内容造成侵权/违法违规/事实不符,请联系编程大学网进行投诉反馈email:xxxxxxxx@qq.com,一经查实,立即删除!

相关文章

系统渐渐沦为“屎山”,原因是..

相信有很多小伙伴都有小猫这样的体会,尤其是接手一个老的系统的时候,总是会吐槽当前的系统很烂,恨不得马上将其完完全全重构掉。分享是最有效的学习方式。 博客:https://blog.ktdaddy.com/背景 小猫维护现有的系统也有一段时间了,踩坑也不少,事故不少。感兴趣的小伙伴可以…

Word设置样式快捷键(转载)

1.问题 每次都要手动选择,有些隔着几个格子比较麻烦,设置快捷键进行管理 2.解决 参考:Word样式也有“快捷键”,你却不知道! (1)单击【开始】-【样式】组,在需要设置快捷键的样式上单击鼠标右键,在弹出的快捷菜单中选择“修改”命令。(2)打开“修改样式”对话框,单击“…

零门槛打造个人图床:感谢Telegraph-Image

零门槛打造个人图床:感谢Telegraph-Image 更好的阅读体验? 幕前小话 很早之前,我就用 GitHub 和 Cloudflare 搭建了自己的图床,不过没多久就发现 cf 自带的 dev 域名被墙了,于是就没再管它。直到上周,我在课上无聊时用手机随便翻了翻后台,没想到竟然又能打开了!并且后台…

在IDEA中使用Gradle存在的显示乱码问题

项目使用Gradle进行依赖管理,当代码中存在错误时,运行程序时Build界面将报错(这是正常的),但是在报错结果中显示乱码信息,如下所示:解决办法:给IDEA添加JVM参数:-Dfile.encoding=UTF-8,然后重启IDEA即可。 参数修改路径:Help -> Edit Custom VM Options...【参考…

基于Rust的Tile-Based游戏开发杂记(02)ggez绘图实操

尽管ggez提供了很多相关特性的demo供运行查看,但笔者第一次使用的时候还是有很多疑惑不解。经过仔细阅读demo代码并结合自己的实践,逐步了解了ggez在不同场景下的绘图方式,在此篇文章进行一定的总结,希望能够帮助到使用ggez的读者。供运行查看,但笔者第一次使用的时候还是…

透视表中不显示“(空白)”字样

问题:数据透视表中不显示“(空白)”字样 解决:数据源中待拖至行字段或列字段的空单元格中填上空格,因其“肉眼”不可见,所以好像空单元格,又不会显示出“(空白)”字样。