擅长:python、mysql、java
<p>下面是一个使用<a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">collections.Counter</a>和设置交集的简单解决方案。其思想是首先分别计算每个列表中每个元素的出现次数;然后,对于每个元素,重叠的数量是两个计数的<code>min</code>。它将一个列表中的每个匹配项与另一个列表中的单个匹配项进行匹配,因此<code>min</code>给出了可以进行匹配的数量。我们只需要计算两个列表中出现的元素,所以我们取两个键集的交集。你知道吗</p>
<p>如果您想计算所有匹配对(即<code>lst1</code>中的每个匹配项都与<code>lst2</code>中的每个匹配项匹配),请将<code>min(c1[k], c2[k])</code>替换为<code>c1[k] * c2[k]</code>。这统计了从<code>lst1</code>和<code>lst2</code>中选择一个匹配项的方法数。你知道吗</p>
<pre><code>from collections import Counter
def count_intersections(lst1, lst2):
c1 = Counter(lst1)
c2 = Counter(lst2)
return { k: min(c1[k], c2[k]) for k in c1.keys() & c2.keys() }
</code></pre>
<p>示例:</p>
<pre class="lang-py prettyprint-override"><code>>>> lst1 = ['a', 'a', 'a', 'b', 'b', 'c', 'e']
>>> lst2 = ['a', 'b', 'b', 'b', 'd', 'e']
>>> count_intersections(lst1, lst2)
{'b': 2, 'a': 1, 'e': 1}
</code></pre>
<p>此解决方案在O(m+n)时间内运行,最多使用O(m+n)辅助空间,其中m和n是两个列表的大小。你知道吗</p>