将两个整型数组按照升序合并,并且过滤掉重复数组元素python
时间: 2023-05-30 13:06:08 浏览: 92
可以使用Python的set()函数来去除重复元素,再将数组合并并排序。
示例代码如下:
```python
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
merged = sorted(set(a + b))
print(merged)
```
输出结果为:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
如果要合并的两个数组本身就是有序的,可以使用双指针法将它们合并,并且在合并过程中去除重复元素。示例代码如下:
```python
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
i = j = 0
merged = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
merged.append(a[i])
i += 1
elif a[i] > b[j]:
merged.append(b[j])
j += 1
else:
merged.append(a[i])
i += 1
j += 1
while i < len(a):
merged.append(a[i])
i += 1
while j < len(b):
merged.append(b[j])
j += 1
print(merged)
```
输出结果同样为:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
阅读全文