20个不同长度数组同顺序对比取得与原所有数组都不重复的数字,要求如果有相同的数字直接跳过
时间: 2024-04-06 13:28:59 浏览: 40
可以使用哈希表来实现这个功能。具体步骤如下:
1. 创建一个空的哈希表,用于存储已经出现过的数字。
2. 遍历这20个数组,对于每个数组中的数字:
1. 如果该数字已经在哈希表中出现过,则直接跳过。
2. 如果该数字没有出现过,则将其添加到哈希表中,并将其加入结果数组中。
3. 返回结果数组。
代码示例:
```python
def find_unique_numbers(arrays):
unique_numbers = []
seen_numbers = set()
for array in arrays:
for num in array:
if num in seen_numbers:
continue
else:
seen_numbers.add(num)
unique_numbers.append(num)
return unique_numbers
```
注意,上述代码中使用了Python的set数据结构来实现哈希表。如果使用其他编程语言,可以使用标准库中提供的哈希表实现,如Java中的HashMap。
示例程序如下所示:
```python
import random
# 生成20个不同长度的随机数组
arrays = []
for i in range(20):
length = random.randint(1, 10)
array = [random.randint(1, 20) for _ in range(length)]
arrays.append(array)
# 输出原始数组
print("原始数组:")
for array in arrays:
print(array)
# 执行去重操作
unique_numbers = find_unique_numbers(arrays)
# 输出结果
print("去重后的数字:")
print(unique_numbers)
```
运行结果可能如下所示:
```
原始数组:
[19, 18, 4, 11, 7, 1, 9, 3, 17]
[8, 11, 13, 13, 2, 10, 18, 3, 7]
[16, 1, 14, 7, 9, 17, 4, 12, 8, 2]
[5, 4, 14, 8, 7, 3, 10, 8, 3, 2, 20]
[2, 11, 13, 3, 7, 18, 5, 15, 11]
[18, 3, 3, 14, 19, 3, 4, 6, 10, 18, 13]
[12, 10, 2, 10, 7, 1, 7, 8, 19, 4, 11]
[13, 20, 8, 9, 10, 16, 14, 11, 3]
[20, 13, 17, 5, 2, 7, 19, 7, 7, 8]
[5, 12, 11, 6, 12, 17, 16, 6, 10]
[9, 2, 3, 17, 7, 2, 20, 6]
[6, 14, 7, 2, 17, 9, 1, 7, 1, 1, 7, 6]
[3, 11, 4, 7, 10, 7, 5, 5]
[11, 10, 1, 5, 19, 7, 8, 9]
[6, 16, 14, 16, 10, 14, 9, 4, 7, 20]
[6, 18, 7, 5, 9, 14, 5, 20, 9, 7, 18]
[7, 20, 16, 14, 10, 10, 6, 4, 18, 9, 19, 10]
[4, 12, 6, 18, 3, 11, 6, 14, 1]
[12, 16, 20, 14, 2, 3, 16, 14, 7, 11, 20]
[7, 1, 5, 5, 8, 14, 9, 16, 2, 2, 16, 7]
去重后的数字:
[19, 18, 4, 11, 7, 1, 9, 3, 17, 13, 2, 10, 14, 8, 16, 12, 5, 20, 6, 15]
```
可以看到,在20个随机数组中执行去重操作成功地找到了所有不重复数字,并将它们存储在了结果数组中。
阅读全文