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.
示例
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
算法思路
比较容易想到的是,用两个循环,两两元素之和与目标数比较,但是算法复杂度为O(n^2),会超时。另一种办法是用字典和枚举,用字典存储查询过的值和索引,用枚举来遍历整个列表,算法复杂度为O(n),所以推荐用第二种方法。
代码实现(python3)
方法一:
1 |
|
方法二:
1 |
|
参考资料
- https://www.tutorialspoint.com/python/python_dictionary.htm Python - Dictionary
- https://www.geeksforgeeks.org/enumerate-in-python/ Enumerate() in Python
- https://leetcode.com/problems/two-sum/ two-sum
Two Sum
https://xiepeng21.cn/posts/e83060be/