Two Sum
Question
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Hint
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Answer
solution:
Knowledge:
enumerate() 函数用于遍历序列中的元素的下标以及元素,这一类问题叫下标元素类。
其常用形式for i, num in enumerate(nums):
下标元素类的问题常常需要用到,单循环加上字典辅助:
注意判断字典中值的方法,直接if a in dict:即可
Last updated
Was this helpful?