当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[LeetCode python] tow sum - 渴望越狱的猫

作者:小梦 来源: 网络 时间: 2024-01-14 阅读:

初始版本:

def twoSum(self, nums, target):    dic = dict() //参考1 {}更快一些    first = 0    sec = 0        for index in range(0, len(nums)): //参考2 xrange更省内存 xrange在python3中被一冲,用range代替        num = nums[index]    if dic.has_key(num): //参考3 has_key在python3中被移除sec = index + 1first = dic[num] + 1break        else:key = target - numdic[key] = index    return [first, sec]
  1. literal({}) is faster

  2. range vs. xrange

  3. in vs. has_key

最终版本:

def twoSum(self, nums, target):    dict = {}        for index in xrange(0, len(nums)):    num = nums[index]    if num in dict:return [dict[num] + 1, index + 1]        else:dict[target - num] = index

网友最爱