题目
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].
题解
使用hash, hash[i]表示i这个数字所在的索引是hash[i], 当在处理第j个节点时,查找hash[target - nums[j]] 是否存在,如果存在则得到解,返回。复杂度o(nlogn)
注意
- 如果使用排序,然后头尾指针遍历,因为需要返回的是索引值,若单纯建立一个hash记录每个元素的下标,会出现数组中有相同元素的时候,不好解决。 所以需要建立一个数据结构,包括该数的值和索引,然后在对数据结构排序。
- 如果暴力枚举i,j则复杂度为\(o(n^2)\), 会超时。
代码
1 | class Solution { |