C++ 建议两个序列中第一个匹配的距离之和的优化算法
我有两个列表,L1和L2,两个列表长度的总和 例如:C++ 建议两个序列中第一个匹配的距离之和的优化算法,c++,c,algorithm,math,C++,C,Algorithm,Math,我有两个列表,L1和L2,两个列表长度的总和 例如: foreach ele N in L1 at position pos if N not in hash hash[N] = pos end-if end-foreach foreach ele N in L2 at position pos if N in hash print pos + hash[N] exit end-if end-foreach print 0 89 145 42 20
foreach ele N in L1 at position pos
if N not in hash
hash[N] = pos
end-if
end-foreach
foreach ele N in L2 at position pos
if N in hash
print pos + hash[N]
exit
end-if
end-foreach
print 0
89 145 42 20 4 16 37 58 89
20 4 16 37 58 89
输出:5
89 145 42 20 4 16 37 58 89
5667812365467
输出:0
1982681001
100 1
输出:5
谢谢
PS:我选择的语言是C和C++,因此标签。
< P>这是一个使用哈希表的线性时间算法。 从L1
的散列元素开始(元素是散列键,索引是值),如果它尚未散列
接下来,对于L2
中的每个元素,查看该元素是否已被散列,如果是,则打印L2
中元素的索引与散列值(同一元素在L1
中的索引)之和并退出
如果在哈希表中未找到L2
元素,则打印0
并退出
算法:
foreach ele N in L1 at position pos
if N not in hash
hash[N] = pos
end-if
end-foreach
foreach ele N in L2 at position pos
if N in hash
print pos + hash[N]
exit
end-if
end-foreach
print 0
将较短的列表添加到哈希(字典)键=编号,值=列表中第一个实例的索引
遍历另一个列表,并尝试在哈希中查找每个元素。匹配完成后,将索引添加到一起(哈希值加上列表中的当前索引)
这在O(n)中运行
boost::unordered_-map或stdex::hash_-map可用于(int-sum=0;sumfor (int sum = 0; sum < a.length + b.length - 1; sum++)
for (int i = 0; i < a.length && i <= sum; i++)
if(a[i] == b[sum-i])
return sum;
return -1;
对于(int i=0;i