我有一个问题,以找到共同的元素在两个数组,这就是不同的尺寸。
I have a problem to find common elements in two arrays and that's of different size.
取,阵列 A1
尺寸 N
和Array A2
尺寸 M
和米!= N
Take , Array A1
of size n
and Array A2
of size m
, and m != n
到目前为止,我已经试过遍历名单一个个元素复制到另一个列表。如果元素已经包含标记,但我知道这不是一个很好的解决方案。
So far, I've tried to iterate lists one by one and copy elements to another list. If the element already contains mark it, but I know it's not a good solution.
推荐答案
排序阵列。然后遍历它们与两个指针,始终推动所述一个指向较小的值。当它们指向相同的值,你有一个共同的价值。这将是为O(n + m),其中n和m是两个列表的大小。这就像在合并归并排序的,但如果你只产生输出时所指出的值是相等的。
Sort the arrays. Then iterate through them with two pointers, always advancing the one pointing to the smaller value. When they point to equal values, you have a common value. This will be O(n+m) where n and m are the sizes of the two lists. It's just like a merge in merge sort, but where you only produce output when the values being pointed to are equal.
def common_elements(a, b):
a.sort()
b.sort()
i, j = 0, 0
common = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
common.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return common
print 'Common values:', ', '.join(map(str, common_elements([1, 2, 4, 8], [1, 4, 9])))
输出
Common values: 1, 4
如果该元素是不可比的,扔从一个列表中的元素融入到一个HashMap和检查元素对HashMap中的第二个列表。
If the elements aren't comparable, throw the elements from one list into a hashmap and check the elements in the second list against the hashmap.
相关推荐
最新文章