【id】#1
【title】TwoSum
【description】
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].
【idea】
- 暴力搜索,两个循环: 时间复杂度
$O(n^{2})$
- Hash查找:时间复杂度 ` O ( n ) O(n) O(n)
建立一个hash字典,遍历list确定因数1,如果(目标-因数1)在字典中,返回两个索引;如果不在字典中,因数1及其索引号存入字典中。
【code】
class Solution:
def twoSum(self,nums,target):
dic={}
for i, val in enumerate(nums):
if target-val in dic:
return [dic[target-val],i]
dic[val] = i
return [-1,-1]
这是一道及其经典的题目,二刷的时候会再来更一下理解,希望那时候能够有所进步啊!