|
| 1 | +import math |
| 2 | + |
| 3 | + |
| 4 | +class SkipList: |
| 5 | + def __init__(self): |
| 6 | + self.data = [] # sorted list |
| 7 | + self.skips = [] # list of skip pointers, each is a tuple (index, value) |
| 8 | + |
| 9 | + def rebuild_skips(self): |
| 10 | + """Rebuild the skip pointer so we can jump over sqrt(n) elements.""" |
| 11 | + n = len(self.data) |
| 12 | + if n == 0: |
| 13 | + self.skips = [] |
| 14 | + return |
| 15 | + |
| 16 | + step = int(math.sqrt(n)) or 1 |
| 17 | + self.skips = list(range(0, n, step)) |
| 18 | + |
| 19 | + def _find_position(self, value): |
| 20 | + """Find the position to insert value using skip pointers.""" |
| 21 | + if not self.data: |
| 22 | + return 0 |
| 23 | + |
| 24 | + # Use skip pointers to find the range where value should be |
| 25 | + for i in range(len(self.skips) - 1): |
| 26 | + a = self.skips[i] |
| 27 | + b = self.skips[i + 1] |
| 28 | + if self.data[a] <= value < self.data[b]: |
| 29 | + # linear search between a and b |
| 30 | + for j in range(a, b): |
| 31 | + if self.data[j] >= value: |
| 32 | + return j |
| 33 | + return b |
| 34 | + |
| 35 | + # Check the last skip pointer |
| 36 | + start = self.skips[-1] |
| 37 | + for j in range(start, len(self.data)): |
| 38 | + if self.data[j] >= value: |
| 39 | + return j |
| 40 | + return len(self.data) |
| 41 | + |
| 42 | + def insert(self, value): |
| 43 | + """Insert value into the skip list, maintaining sorted order.""" |
| 44 | + pos = self._find_position(value) |
| 45 | + |
| 46 | + if pos < len(self.data) and self.data[pos] == value: |
| 47 | + return # value already exists, do not insert duplicates |
| 48 | + self.data.insert(pos, value) |
| 49 | + self.rebuild_skips() |
| 50 | + |
| 51 | + def __contains__(self, value): |
| 52 | + if not self.data: |
| 53 | + return False |
| 54 | + |
| 55 | + for i in range(len(self.skips) - 1): |
| 56 | + a = self.skips[i] |
| 57 | + b = self.skips[i + 1] |
| 58 | + if self.data[a] <= value < self.data[b]: |
| 59 | + return value in self.data[a:b] |
| 60 | + |
| 61 | + start = self.skips[-1] |
| 62 | + return value in self.data[start::] |
| 63 | + |
| 64 | + def to_list(self): |
| 65 | + """Return the skip list as a regular sorted list.""" |
| 66 | + return self.data |
0 commit comments