Python:检查两个数组(可能包含重复的元素)是否包含同一组元素



我正在尝试解决家庭作业问题。

Q. 假设存在两个数组 X 和 Y 的 m 个元素。假设它们可能包含重复项(即重复元素),在其上定义了总顺序关系。 a) 开发一种有效的算法来确定 X 和 Y 是否包含相同的 元素集。

现在,为了尽可能高效,有人建议使用哈希表。我一直在努力实现它。

我已经创建了数组和哈希表,然后将一个数组导入到哈希表中。

在这一点上,我正在寻找最有效的方法来搜索数组并给我答案。

dict = {'0':'-','1':'a','2':'b','3':'c'} #declare dictionary
print "first element of dict = ", dict['0']
print "n"
array1 = ["4","5","6","7","8","9","10"]
print "array 1 = ", array1
array2 = ["4","5","6","7","8","9","10"]
print "array 2 = ", array2
print "n"
print "array1[3] = ", array1[3]
print "n"
print "clearing dictionary..."
dict.clear(); 
print "dict = ", dict
print "n"
x = 0 #iterator for array1
print "importing array1 into dictionary..."
while x < len(array1) :
dict[x] = array1[x]
x += 1
print dict
y = 0 #iterator for array2
while y < len(array2) :
if dict

如果有人能进一步指导我在这里需要的逻辑,那将不胜感激。

这是我的解决方案。这是最有效的解决方案吗?时间复杂度是多少?我猜是O(n)。我说的对吗?

# define first array
array1 = ["1","1","1","2"]
print "array 1 = ", array1
#define second array
array2 = ["1","2","3"]
print "array 2 = ", array2
#function
def is_empty(x, y):
#find set difference between first and second array
difference1 = set(x) - set(y)
print difference1
#find set difference between second and first array
difference2 = set(y) - set(x)
print difference2
#union two differences together
finalset = difference1.union(difference2)
print finalset
#if there are elements in finalset, arrays do not contain same set of elements
if finalset:
print('The sets do not contain the same set of elements.')
return False
#if there are no elements in final set, arrays contain same set of elements
else:
print('The sets contain the same set of elements.')
return True
#function call on two arrays
is_empty(array1, array2)

相关内容

  • 没有找到相关文章

最新更新