今天的每日一题是困难题,但最多只能算中等,看到以前自己的Python解真是自己跟自己找麻烦,弄的自己哭笑不得。
1206. 设计跳表
class Skiplist
def initialize()
@h = {}
end
=begin
:type target: Integer
:rtype: Boolean
=end
def search(target)
@h.has_key?(target)
end
=begin
:type num: Integer
:rtype: Void
=end
def add(num)
if @h.has_key?(num)
@h[num] += 1
else
@h[num] = 1
end
end
=begin
:type num: Integer
:rtype: Boolean
=end
def erase(num)
if @h.has_key?(num)
@h[num] -= 1
if @h[num] == 0
@h.delete(num)
end
return true
else
return false
end
end
end
# Your Skiplist object will be instantiated and called as such:
# obj = Skiplist.new()
# param_1 = obj.search(target)
# obj.add(num)
# param_3 = obj.erase(num)
如下是Python直译解
class Skiplist:
def __init__(self):
self.h = {}
def search(self, target: int) -> bool:
return target in self.h.keys()
def add(self, num: int) -> None:
if num in self.h.keys():
self.h[num] += 1
else:
self.h[num] = 1
def erase(self, num: int) -> bool:
if num in self.h.keys():
self.h[num] -= 1
if self.h[num] == 0:
del self.h[num]
return True
else:
return False
# 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)
如下是自己跟自己找麻烦的Python解
from sortedcontainers import SortedList
class Skiplist:
def __init__(self):
self.num1 = SortedList([])
def search(self, target: int) -> bool:
n = bisect.bisect_left(self.num1,target)
if n >= len(self.num1):
return False
elif self.num1[n] == target:
return True
else:
return False
def add(self, num: int) -> None:
self.num1.add(num)
def erase(self, num: int) -> bool:
n = bisect.bisect_left(self.num1,num)
if n >= len(self.num1):
return False
elif self.num1[n] == num:
self.num1.discard(num)
return True
else:
return False