[LeetCode python] tow sum - 渴望越狱的猫
初始版本:
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]
literal({}) is faster
range vs. xrange
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