题目描述:
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].
题意:给定目标值,在数组中查找到两数满足两数相加等于目标值,返回两数索引,此题已经说明每个目标值都只有唯一一组数符合
时间复杂度: 暴力搜索:O(n^2)
采用哈希搜索法:O(n)
python可利用字典,建立的索引为key-value:数值-索引
python版---map
class Solution(object):
def twoSum(self, nums, target):
dict = {}
for i in range(len(nums)):
if target - nums[i] in dict # target-nums[i]为key ( 索引 下标 )
return [dict[target - num[i]], i]
dict[nums[i]] = i
return []
# 字典中的key < == > 列表、元组、字符串 中的[下标、索引]
C++版---map
用map实现,建立元素与下标的映射! 找到和为target的元素,返回下标
vector <int> twoSum(vector<int> nums, int target)
{
vector<int> res;
map<int, int> m;
for(int i=0; i< nums.size(); i++)
{
if(m.find(target - num[i]!=m.end())
{
res.push_back(m[target-nums[i]]);
res.push_back(i);
}
m[nums[i]] = i;
}
return res;
}
reference :
python: https://blog.csdn.net/qq_28119401/article/details/52972461