Leetcode 1206 (用Ruby真是方便)

今天的每日一题是困难题,但最多只能算中等,看到以前自己的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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容