作为一个非通信非计算机但是硕士念了数学的妹纸,我想说,还是开始学着刷leecode吧。
欢迎大家指出错误
欢迎大佬伸出自己的大腿
各种求抱大腿
开始的代码一边看youtube一边学
嘤嘤嘤~
23333
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
哈希表解法1
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i ,num in enumerate(nums):
dict[num] = i
for i ,num in enumerate(nums):
if target-num in dict and dict[target-num] !=i:
return (i, dict[target -num])
稍微优化一下,不用写两个enumerate的话,
dict = {}
for i ,num in enumerate(nums):
if target-num in dict:
return(i,dict[target-num])
else:
dict[num] = i
提升了一些。
enumerate 查一下,文档中是这样用的:(来源于 菜鸟教程)
Python enumerate() 函数
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
Python 2.3. 以上版本可用,2.6 添加 start 参数。
语法
以下是 enumerate() 方法的语法:
enumerate(sequence, [start=0])
参数
- sequence -- 一个序列、迭代器或其他支持迭代对象。
- start -- 下标起始位置。
返回值
返回 enumerate(枚举) 对象。
实例
以下展示了使用 enumerate() 方法的实例:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) # 小标从 1 开始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的 for 循环
>>>i = 0 >>> seq = ['one', 'two', 'three'] >>> for element in seq: ... print i, seq[i] ... i +=1 ... 0 one 1 two 2 three
for 循环使用 enumerate
>>>seq = ['one', 'two', 'three'] >>> for i, element in enumerate(seq): ... print i, element ... 0 one 1 two 2 three