题目描述:
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版---字典---适用于匹配一对
def twoSum(nums, target):
dict = {}
for index_i,value_i in enumerate(nums):
value_j = target - value_i
if value_j not in dict:
dict[value_i] = index_i
else:
index_j = dict[value_j]
return [index_i, index_j]
return []
# 字典中的key < == > 列表、元组、字符串 中的[下标、索引]
python版---字典---适合多对匹配
思路:用字典与遍历列表nums的所有值,并依次将遍历的每个值与已经遍历且没有匹配的值进行匹配
dict用来记录已遍历且没有匹配的值;indexList记录已匹配的下标
def twoSum(nums, target):
indexList = []
dict = {}
for index_i, value_i in enumerate(nums):
value_j = target - value_i
if value_j not in dict:
dict[value_i] = index_i
else:
index_j = dict[value_j]
indexList.append([index_i, index_j])
return listList
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.youkuaiyun.com/qq_28119401/article/details/52972461
以上原理和code 均输出单对结果(适用于 有序 一对结果)
以下reference输出多对结果(如果存在多对 无序)
博客围绕在数组中查找两数相加等于目标值并返回其索引的问题展开。介绍了暴力搜索和哈希搜索两种方法,给出了Python利用字典、C++用map实现的代码思路,还提及了单对和多对结果的不同实现及参考链接。
1万+

被折叠的 条评论
为什么被折叠?



