链接:https://www.nowcoder.com/questionTerminal/20ef0972485e41019e39543e8e895b7f
来源:牛客网
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=17
Output: index1=0, index2=3
这里用了enumerate()函数,这篇博客有介绍https://www.runoob.com/python/python-func-enumerate.html
该函数直接可以返回索引和数值,但是该函数历遍全部数据浪费时间和资源
>>>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循环也是很好用上面博客有详细例子。
https://jingyan.baidu.com/article/9c69d48fdc09c413c9024e1f.html该链接讲述了多种实现方式,适合入门级别的我观摩。